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.
#ifndef UI_VIEWS_WIDGET_WIDGET_UTILS_MAC_H_
#define UI_VIEWS_WIDGET_WIDGET_UTILS_MAC_H_
#include "ui/views/views_export.h"
#include "ui/views/widget/widget.h"
namespace views {
gfx::Size GetWindowSizeForClientSize(Widget* widget, const gfx::Size& size);
} // namespace views
#endif // UI_VIEWS_WIDGET_WIDGET_UTILS_MAC_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget_utils_mac.h | C++ | unknown | 472 |
// 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_mac.h"
#import "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h"
namespace views {
gfx::Size GetWindowSizeForClientSize(Widget* widget, const gfx::Size& size) {
DCHECK(widget);
return remote_cocoa::NativeWidgetNSWindowBridge::GetWindowSizeForClientSize(
widget->GetNativeWindow().GetNativeNSWindow(), size);
}
bool IsNSToolbarFullScreenWindow(NSWindow* window) {
// TODO(bur): Investigate other approaches to detecting
// NSToolbarFullScreenWindow. This is a private class and the name could
// change.
return [window isKindOfClass:NSClassFromString(@"NSToolbarFullScreenWindow")];
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget_utils_mac.mm | Objective-C++ | unknown | 830 |
// 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/window_reorderer.h"
#include <stddef.h>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include "base/containers/adapters.h"
#include "base/memory/raw_ptr.h"
#include "ui/aura/window.h"
#include "ui/aura/window_occlusion_tracker.h"
#include "ui/compositor/layer.h"
#include "ui/views/view.h"
#include "ui/views/view_constants_aura.h"
namespace views {
namespace {
// Sets |hosted_windows| to a mapping of the views with an associated window to
// the window that they are associated to. Only views associated to a child of
// |parent_window| are returned.
void GetViewsWithAssociatedWindow(
const aura::Window& parent_window,
std::map<views::View*, aura::Window*>* hosted_windows) {
for (auto* child : parent_window.children()) {
View* host_view = child->GetProperty(kHostViewKey);
if (host_view)
(*hosted_windows)[host_view] = child;
}
}
// Sets |order| to the list of views whose layer / associated window's layer
// is a child of |parent_layer|. |order| is sorted in ascending z-order of
// the views.
// |hosts| are the views with an associated window whose layer is a child of
// |parent_layer|.
void GetOrderOfViewsWithLayers(
views::View* view,
ui::Layer* parent_layer,
const std::map<views::View*, aura::Window*>& hosts,
std::vector<views::View*>* order) {
DCHECK(view);
DCHECK(parent_layer);
DCHECK(order);
if (view->layer() && view->layer()->parent() == parent_layer) {
order->push_back(view);
// |hosts| may contain a child of |view|.
} else if (hosts.find(view) != hosts.end()) {
order->push_back(view);
}
for (views::View* child : view->GetChildrenInZOrder())
GetOrderOfViewsWithLayers(child, parent_layer, hosts, order);
}
} // namespace
// Class which reorders windows as a result of the kHostViewKey property being
// set on the window.
class WindowReorderer::AssociationObserver : public aura::WindowObserver {
public:
explicit AssociationObserver(WindowReorderer* reorderer);
AssociationObserver(const AssociationObserver&) = delete;
AssociationObserver& operator=(const AssociationObserver&) = delete;
~AssociationObserver() override;
// Start/stop observing changes in the kHostViewKey property on |window|.
void StartObserving(aura::Window* window);
void StopObserving(aura::Window* window);
private:
// aura::WindowObserver overrides:
void OnWindowPropertyChanged(aura::Window* window,
const void* key,
intptr_t old) override;
void OnWindowDestroying(aura::Window* window) override;
// Not owned.
raw_ptr<WindowReorderer> reorderer_;
std::set<aura::Window*> windows_;
};
WindowReorderer::AssociationObserver::AssociationObserver(
WindowReorderer* reorderer)
: reorderer_(reorderer) {}
WindowReorderer::AssociationObserver::~AssociationObserver() {
while (!windows_.empty())
StopObserving(*windows_.begin());
}
void WindowReorderer::AssociationObserver::StartObserving(
aura::Window* window) {
windows_.insert(window);
window->AddObserver(this);
}
void WindowReorderer::AssociationObserver::StopObserving(aura::Window* window) {
windows_.erase(window);
window->RemoveObserver(this);
}
void WindowReorderer::AssociationObserver::OnWindowPropertyChanged(
aura::Window* window,
const void* key,
intptr_t old) {
if (key == kHostViewKey)
reorderer_->ReorderChildWindows();
}
void WindowReorderer::AssociationObserver::OnWindowDestroying(
aura::Window* window) {
windows_.erase(window);
window->RemoveObserver(this);
}
WindowReorderer::WindowReorderer(aura::Window* parent_window, View* root_view)
: parent_window_(parent_window),
root_view_(root_view),
association_observer_(new AssociationObserver(this)) {
parent_window_->AddObserver(this);
for (auto* window : parent_window_->children())
association_observer_->StartObserving(window);
ReorderChildWindows();
}
WindowReorderer::~WindowReorderer() {
if (parent_window_) {
parent_window_->RemoveObserver(this);
// |association_observer_| stops observing any windows it is observing upon
// destruction.
}
}
void WindowReorderer::ReorderChildWindows() {
if (!parent_window_)
return;
std::map<View*, aura::Window*> hosted_windows;
GetViewsWithAssociatedWindow(*parent_window_, &hosted_windows);
if (hosted_windows.empty()) {
// Exit early if there are no views with associated windows.
// View::ReorderLayers() should have already reordered the layers owned by
// views.
return;
}
// Compute the desired z-order of the layers based on the order of the views
// with layers and views with associated windows in the view tree.
std::vector<View*> view_with_layer_order;
GetOrderOfViewsWithLayers(root_view_, parent_window_->layer(), hosted_windows,
&view_with_layer_order);
std::vector<ui::Layer*> children_layer_order;
aura::WindowOcclusionTracker::ScopedPause pause_occlusion_tracking;
// For the sake of simplicity, reorder both the layers owned by views and the
// layers of windows associated with a view. Iterate through
// |view_with_layer_order| backwards and stack windows at the bottom so that
// windows not associated to a view are stacked above windows with an
// associated view.
for (View* view : base::Reversed(view_with_layer_order)) {
std::vector<ui::Layer*> layers;
aura::Window* window = nullptr;
auto hosted_window_it = hosted_windows.find(view);
if (hosted_window_it != hosted_windows.end()) {
window = hosted_window_it->second;
layers.push_back(window->layer());
} else {
layers = view->GetLayersInOrder();
std::reverse(layers.begin(), layers.end());
}
DCHECK(!layers.empty());
if (window)
parent_window_->StackChildAtBottom(window);
for (ui::Layer* layer : layers)
children_layer_order.emplace_back(layer);
}
std::reverse(children_layer_order.begin(), children_layer_order.end());
parent_window_->layer()->StackChildrenAtBottom(children_layer_order);
}
void WindowReorderer::OnWindowAdded(aura::Window* new_window) {
association_observer_->StartObserving(new_window);
ReorderChildWindows();
}
void WindowReorderer::OnWillRemoveWindow(aura::Window* window) {
association_observer_->StopObserving(window);
}
void WindowReorderer::OnWindowDestroying(aura::Window* window) {
parent_window_->RemoveObserver(this);
parent_window_ = nullptr;
association_observer_.reset();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/window_reorderer.cc | C++ | unknown | 6,734 |
// 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_WINDOW_REORDERER_H_
#define UI_VIEWS_WIDGET_WINDOW_REORDERER_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "ui/aura/window_observer.h"
namespace aura {
class Window;
}
namespace views {
class View;
// Class which reorders the widget's child windows which have an associated view
// in the widget's view tree according the z-order of the views in the view
// tree. Windows not associated to a view are stacked above windows with an
// associated view. The child windows' layers are additionally reordered
// according to the z-order of the associated views relative to views with
// layers.
class WindowReorderer : public aura::WindowObserver {
public:
WindowReorderer(aura::Window* window, View* root_view);
WindowReorderer(const WindowReorderer&) = delete;
WindowReorderer& operator=(const WindowReorderer&) = delete;
~WindowReorderer() override;
// Explicitly reorder the children of |window_| (and their layers). This
// method should be called when the position of a view with an associated
// window changes in the view hierarchy. This method assumes that the
// child layers of |window_| which are owned by views are already in the
// correct z-order relative to each other and does no reordering if there
// are no views with an associated window.
void ReorderChildWindows();
private:
// aura::WindowObserver overrides:
void OnWindowAdded(aura::Window* new_window) override;
void OnWillRemoveWindow(aura::Window* window) override;
void OnWindowDestroying(aura::Window* window) override;
// The window and the root view of the native widget which owns the
// WindowReorderer.
raw_ptr<aura::Window> parent_window_;
raw_ptr<View> root_view_;
// Reorders windows as a result of the kHostViewKey being set on a child of
// |parent_window_|.
class AssociationObserver;
std::unique_ptr<AssociationObserver> association_observer_;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_WINDOW_REORDERER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/window_reorderer.h | C++ | unknown | 2,148 |
// 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 <memory>
#include "base/memory/raw_ptr.h"
#include "ui/aura/test/test_windows.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/test/test_layers.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/view.h"
#include "ui/views/view_constants_aura.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
// Sets the name of |window| and |window|'s layer to |name|.
void SetWindowAndLayerName(aura::Window* window, const std::string& name) {
window->SetName(name);
window->layer()->SetName(name);
}
// Returns a string containing the name of each of the child windows (bottommost
// first) of |parent|. The format of the string is "name1 name2 name3 ...".
std::string ChildWindowNamesAsString(const aura::Window& parent) {
std::string names;
for (const auto* child : parent.children()) {
if (!names.empty())
names += " ";
names += child->GetName();
}
return names;
}
class WindowReordererTest : public ViewsTestBase {
public:
Widget::InitParams CreateParams(Widget::InitParams::Type type) override {
Widget::InitParams params = ViewsTestBase::CreateParams(type);
params.parent = parent_;
return params;
}
std::unique_ptr<Widget> CreateControlWidget(aura::Window* parent) {
parent_ = parent;
return CreateTestWidget(Widget::InitParams::TYPE_CONTROL);
}
private:
raw_ptr<aura::Window> parent_ = nullptr;
};
// Test that views with layers and views with associated windows are reordered
// according to the view hierarchy.
TEST_F(WindowReordererTest, Basic) {
std::unique_ptr<Widget> parent = CreateControlWidget(root_window());
parent->Show();
aura::Window* parent_window = parent->GetNativeWindow();
View* contents_view = parent->SetContentsView(std::make_unique<View>());
// 1) Test that layers for views and layers for windows associated to a host
// view are stacked below the layers for any windows not associated to a host
// view.
View* v = new View();
v->SetPaintToLayer();
v->layer()->SetName("v");
contents_view->AddChildView(v);
std::unique_ptr<Widget> w1 = CreateControlWidget(parent_window);
SetWindowAndLayerName(w1->GetNativeView(), "w1");
w1->Show();
std::unique_ptr<Widget> w2 = CreateControlWidget(parent_window);
SetWindowAndLayerName(w2->GetNativeView(), "w2");
w2->Show();
EXPECT_EQ("w1 w2", ChildWindowNamesAsString(*parent_window));
EXPECT_EQ("v w1 w2",
ui::test::ChildLayerNamesAsString(*parent_window->layer()));
View* host_view2 = new View();
contents_view->AddChildView(host_view2);
w2->GetNativeView()->SetProperty(kHostViewKey, host_view2);
EXPECT_EQ("w2 w1", ChildWindowNamesAsString(*parent_window));
EXPECT_EQ("v w2 w1",
ui::test::ChildLayerNamesAsString(*parent_window->layer()));
View* host_view1 = new View();
w1->GetNativeView()->SetProperty(kHostViewKey, host_view1);
contents_view->AddChildViewAt(host_view1, 0);
EXPECT_EQ("w1 w2", ChildWindowNamesAsString(*parent_window));
EXPECT_EQ("w1 v w2",
ui::test::ChildLayerNamesAsString(*parent_window->layer()));
// 2) Test the z-order of the windows and layers as a result of reordering the
// views.
contents_view->ReorderChildView(host_view1, contents_view->children().size());
EXPECT_EQ("w2 w1", ChildWindowNamesAsString(*parent_window));
EXPECT_EQ("v w2 w1",
ui::test::ChildLayerNamesAsString(*parent_window->layer()));
contents_view->ReorderChildView(host_view2, contents_view->children().size());
EXPECT_EQ("w1 w2", ChildWindowNamesAsString(*parent_window));
EXPECT_EQ("v w1 w2",
ui::test::ChildLayerNamesAsString(*parent_window->layer()));
// 3) Test the z-order of the windows and layers as a result of reordering the
// views in situations where the window order remains unchanged.
contents_view->ReorderChildView(v, contents_view->children().size());
EXPECT_EQ("w1 w2", ChildWindowNamesAsString(*parent_window));
EXPECT_EQ("w1 w2 v",
ui::test::ChildLayerNamesAsString(*parent_window->layer()));
contents_view->ReorderChildView(host_view2, contents_view->children().size());
EXPECT_EQ("w1 w2", ChildWindowNamesAsString(*parent_window));
EXPECT_EQ("w1 v w2",
ui::test::ChildLayerNamesAsString(*parent_window->layer()));
}
// Test that different orderings of:
// - adding a window to a parent widget
// - adding a "host" view to a parent widget
// - associating the "host" view and window
// all correctly reorder the child windows and layers.
TEST_F(WindowReordererTest, Association) {
std::unique_ptr<Widget> parent = CreateControlWidget(root_window());
parent->Show();
aura::Window* parent_window = parent->GetNativeWindow();
View* contents_view = parent->SetContentsView(std::make_unique<View>());
aura::Window* w1 =
aura::test::CreateTestWindowWithId(0, parent->GetNativeWindow());
SetWindowAndLayerName(w1, "w1");
aura::Window* w2 = aura::test::CreateTestWindowWithId(0, nullptr);
SetWindowAndLayerName(w2, "w2");
View* host_view2 = new View();
// 1) Test that parenting the window to the parent widget last results in a
// correct ordering of child windows and layers.
contents_view->AddChildView(host_view2);
w2->SetProperty(views::kHostViewKey, host_view2);
EXPECT_EQ("w1", ChildWindowNamesAsString(*parent_window));
EXPECT_EQ("w1", ui::test::ChildLayerNamesAsString(*parent_window->layer()));
parent_window->AddChild(w2);
EXPECT_EQ("w2 w1", ChildWindowNamesAsString(*parent_window));
EXPECT_EQ("w2 w1",
ui::test::ChildLayerNamesAsString(*parent_window->layer()));
// 2) Test that associating the window and "host" view last results in a
// correct ordering of child windows and layers.
View* host_view1 = new View();
contents_view->AddChildViewAt(host_view1, 0);
EXPECT_EQ("w2 w1", ChildWindowNamesAsString(*parent_window));
EXPECT_EQ("w2 w1",
ui::test::ChildLayerNamesAsString(*parent_window->layer()));
w1->SetProperty(views::kHostViewKey, host_view1);
EXPECT_EQ("w1 w2", ChildWindowNamesAsString(*parent_window));
EXPECT_EQ("w1 w2",
ui::test::ChildLayerNamesAsString(*parent_window->layer()));
// 3) Test that parenting the "host" view to the parent widget last results
// in a correct ordering of child windows and layers.
contents_view->RemoveChildView(host_view2);
contents_view->AddChildViewAt(host_view2, 0);
EXPECT_EQ("w2 w1", ChildWindowNamesAsString(*parent_window));
EXPECT_EQ("w2 w1",
ui::test::ChildLayerNamesAsString(*parent_window->layer()));
}
// It is possible to associate a window to a view which has a parent layer
// (other than the widget layer). In this case, the parent layer of the host
// view and the parent layer of the associated window are different. Test that
// the layers and windows are properly reordered in this case.
TEST_F(WindowReordererTest, HostViewParentHasLayer) {
std::unique_ptr<Widget> parent = CreateControlWidget(root_window());
parent->Show();
aura::Window* parent_window = parent->GetNativeWindow();
View* contents_view = parent->SetContentsView(std::make_unique<View>());
// Create the following view hierarchy. (*) denotes views which paint to a
// layer.
//
// contents_view
// +-- v1
// +-- v11*
// +-- v12 (attached window)
// +-- v13*
// +--v2*
View* v1 = new View();
contents_view->AddChildView(v1);
View* v11 = new View();
v11->SetPaintToLayer();
v11->layer()->SetName("v11");
v1->AddChildView(v11);
std::unique_ptr<Widget> w = CreateControlWidget(parent_window);
SetWindowAndLayerName(w->GetNativeView(), "w");
w->Show();
View* v12 = new View();
v1->AddChildView(v12);
w->GetNativeView()->SetProperty(kHostViewKey, v12);
View* v13 = new View();
v13->SetPaintToLayer();
v13->layer()->SetName("v13");
v1->AddChildView(v13);
View* v2 = new View();
v2->SetPaintToLayer();
v2->layer()->SetName("v2");
contents_view->AddChildView(v2);
// Test intial state.
EXPECT_EQ("w", ChildWindowNamesAsString(*parent_window));
EXPECT_EQ("v11 w v13 v2",
ui::test::ChildLayerNamesAsString(*parent_window->layer()));
// |w|'s layer should be stacked above |v1|'s layer.
v1->SetPaintToLayer();
v1->layer()->SetName("v1");
EXPECT_EQ("w", ChildWindowNamesAsString(*parent_window));
EXPECT_EQ("v1 w v2",
ui::test::ChildLayerNamesAsString(*parent_window->layer()));
// Test moving the host view from one view with a layer to another.
v1->RemoveChildView(v12);
v2->AddChildView(v12);
EXPECT_EQ("w", ChildWindowNamesAsString(*parent_window));
EXPECT_EQ("v1 v2 w",
ui::test::ChildLayerNamesAsString(*parent_window->layer()));
}
// Test that a layer added beneath a view is restacked correctly.
TEST_F(WindowReordererTest, ViewWithLayerBeneath) {
std::unique_ptr<Widget> parent = CreateControlWidget(root_window());
parent->Show();
aura::Window* parent_window = parent->GetNativeWindow();
View* contents_view = parent->SetContentsView(std::make_unique<View>());
View* view_with_layer_beneath =
contents_view->AddChildView(std::make_unique<View>());
ui::Layer layer_beneath;
view_with_layer_beneath->AddLayerToRegion(&layer_beneath,
LayerRegion::kBelow);
ASSERT_NE(nullptr, view_with_layer_beneath->layer());
view_with_layer_beneath->layer()->SetName("view");
layer_beneath.SetName("beneath");
// Verify that the initial ordering is correct.
EXPECT_EQ("beneath view",
ui::test::ChildLayerNamesAsString(*parent_window->layer()));
// Add a hosted window to make WindowReorderer::ReorderChildWindows() restack
// layers.
std::unique_ptr<Widget> child_widget = CreateControlWidget(parent_window);
SetWindowAndLayerName(child_widget->GetNativeView(), "child_widget");
child_widget->Show();
View* host_view = contents_view->AddChildView(std::make_unique<View>());
child_widget->GetNativeView()->SetProperty(kHostViewKey, host_view);
// Verify the new order is correct.
EXPECT_EQ("beneath view child_widget",
ui::test::ChildLayerNamesAsString(*parent_window->layer()));
}
} // namespace
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/window_reorderer_unittest.cc | C++ | unknown | 10,447 |
# hwnd_util is allowed to include ui/views because it has separate
# implementations for win and aura.
specific_include_rules = {
"hwnd_util.*": [
"+ui/views",
],
}
# The rest of the code here is intended to be distinct from the rest of
# views and not depend on the details of the win and aura implementations.
# Use HWNDMessageHandlerDelegate instead of #including views types.
include_rules = [
"-ui/views",
"+base",
"+services/tracing/public",
"+third_party/perfetto/protos/perfetto/trace/track_event",
"+ui/base",
"+ui/gfx",
"+ui/latency",
"+ui/views/accessibility/native_view_accessibility_win.h",
"+ui/views/ime/input_method_delegate.h",
"+ui/views/views_delegate.h",
"+ui/views/views_export.h",
"+ui/views/widget/widget_hwnd_utils.h",
"+ui/views/win",
"+ui/views/window/window_resize_utils.h",
]
| Zhao-PengFei35/chromium_src_4 | ui/views/win/DEPS | Python | unknown | 842 |
// 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/win/fullscreen_handler.h"
#include <memory>
#include "base/win/win_util.h"
#include "ui/display/types/display_constants.h"
#include "ui/display/win/screen_win.h"
#include "ui/display/win/screen_win_display.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/win/scoped_fullscreen_visibility.h"
namespace views {
////////////////////////////////////////////////////////////////////////////////
// FullscreenHandler, public:
FullscreenHandler::FullscreenHandler() = default;
FullscreenHandler::~FullscreenHandler() = default;
void FullscreenHandler::SetFullscreen(bool fullscreen,
int64_t target_display_id) {
if (fullscreen_ == fullscreen &&
target_display_id == display::kInvalidDisplayId) {
return;
}
ProcessFullscreen(fullscreen, target_display_id);
}
void FullscreenHandler::MarkFullscreen(bool fullscreen) {
if (!task_bar_list_) {
HRESULT hr =
::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&task_bar_list_));
if (SUCCEEDED(hr) && FAILED(task_bar_list_->HrInit()))
task_bar_list_ = nullptr;
}
// As per MSDN marking the window as fullscreen should ensure that the
// taskbar is moved to the bottom of the Z-order when the fullscreen window
// is activated. If the window is not fullscreen, the Shell falls back to
// heuristics to determine how the window should be treated, which means
// that it could still consider the window as fullscreen. :(
if (task_bar_list_)
task_bar_list_->MarkFullscreenWindow(hwnd_, !!fullscreen);
}
gfx::Rect FullscreenHandler::GetRestoreBounds() const {
return gfx::Rect(saved_window_info_.rect);
}
////////////////////////////////////////////////////////////////////////////////
// FullscreenHandler, private:
void FullscreenHandler::ProcessFullscreen(bool fullscreen,
int64_t target_display_id) {
std::unique_ptr<ScopedFullscreenVisibility> visibility;
// Save current window state if not already fullscreen.
if (!fullscreen_) {
saved_window_info_.style = GetWindowLong(hwnd_, GWL_STYLE);
saved_window_info_.ex_style = GetWindowLong(hwnd_, GWL_EXSTYLE);
// Store the original window rect, DPI, and monitor info to detect changes
// and more accurately restore window placements when exiting fullscreen.
::GetWindowRect(hwnd_, &saved_window_info_.rect);
saved_window_info_.dpi = display::win::ScreenWin::GetDPIForHWND(hwnd_);
saved_window_info_.monitor =
MonitorFromWindow(hwnd_, MONITOR_DEFAULTTONEAREST);
saved_window_info_.monitor_info.cbSize =
sizeof(saved_window_info_.monitor_info);
GetMonitorInfo(saved_window_info_.monitor,
&saved_window_info_.monitor_info);
}
fullscreen_ = fullscreen;
auto ref = weak_ptr_factory_.GetWeakPtr();
if (fullscreen_) {
// Set new window style and size.
SetWindowLong(hwnd_, GWL_STYLE,
saved_window_info_.style & ~(WS_CAPTION | WS_THICKFRAME));
SetWindowLong(
hwnd_, GWL_EXSTYLE,
saved_window_info_.ex_style & ~(WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE |
WS_EX_CLIENTEDGE | WS_EX_STATICEDGE));
// Set the window rect to the rcMonitor of the targeted or current display.
const display::win::ScreenWinDisplay screen_win_display =
display::win::ScreenWin::GetScreenWinDisplayWithDisplayId(
target_display_id);
gfx::Rect window_rect = screen_win_display.screen_rect();
if (target_display_id == display::kInvalidDisplayId ||
screen_win_display.display().id() != target_display_id) {
HMONITOR monitor = MonitorFromWindow(hwnd_, MONITOR_DEFAULTTONEAREST);
MONITORINFO monitor_info;
monitor_info.cbSize = sizeof(monitor_info);
GetMonitorInfo(monitor, &monitor_info);
window_rect = gfx::Rect(monitor_info.rcMonitor);
}
SetWindowPos(hwnd_, nullptr, window_rect.x(), window_rect.y(),
window_rect.width(), window_rect.height(),
SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
} else {
// Restore the window style and bounds saved prior to entering fullscreen.
// Use WS_VISIBLE for windows shown after SetFullscreen: crbug.com/1062251.
// Making multiple window adjustments here is ugly, but if SetWindowPos()
// doesn't redraw, the taskbar won't be repainted.
SetWindowLong(hwnd_, GWL_STYLE, saved_window_info_.style | WS_VISIBLE);
SetWindowLong(hwnd_, GWL_EXSTYLE, saved_window_info_.ex_style);
gfx::Rect window_rect(saved_window_info_.rect);
HMONITOR monitor =
MonitorFromRect(&saved_window_info_.rect, MONITOR_DEFAULTTONEAREST);
MONITORINFO monitor_info;
monitor_info.cbSize = sizeof(monitor_info);
GetMonitorInfo(monitor, &monitor_info);
// Adjust the window bounds to restore, if displays were disconnected,
// virtually rearranged, or otherwise changed metrics during fullscreen.
if (monitor != saved_window_info_.monitor ||
gfx::Rect(saved_window_info_.monitor_info.rcWork) !=
gfx::Rect(monitor_info.rcWork)) {
window_rect.AdjustToFit(gfx::Rect(monitor_info.rcWork));
}
const int fullscreen_dpi = display::win::ScreenWin::GetDPIForHWND(hwnd_);
SetWindowPos(hwnd_, nullptr, window_rect.x(), window_rect.y(),
window_rect.width(), window_rect.height(),
SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
const int final_dpi = display::win::ScreenWin::GetDPIForHWND(hwnd_);
if (final_dpi != saved_window_info_.dpi || final_dpi != fullscreen_dpi) {
// Reissue SetWindowPos if the DPI changed from saved or fullscreen DPIs.
// The first call may misinterpret bounds spanning displays, if the
// fullscreen display's DPI does not match the target display's DPI.
//
// Scale and clamp the bounds if the final DPI changed from the saved DPI.
// This more accurately matches the original placement, while avoiding
// unexpected offscreen placement in a recongifured multi-screen space.
if (final_dpi != saved_window_info_.dpi) {
gfx::SizeF size(window_rect.size());
size.Scale(final_dpi / static_cast<float>(saved_window_info_.dpi));
window_rect.set_size(gfx::ToCeiledSize(size));
window_rect.AdjustToFit(gfx::Rect(monitor_info.rcWork));
}
SetWindowPos(hwnd_, nullptr, window_rect.x(), window_rect.y(),
window_rect.width(), window_rect.height(),
SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
}
}
if (!ref)
return;
MarkFullscreen(fullscreen);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/win/fullscreen_handler.cc | C++ | unknown | 6,899 |
// 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_WIN_FULLSCREEN_HANDLER_H_
#define UI_VIEWS_WIN_FULLSCREEN_HANDLER_H_
#include <shobjidl.h>
#include <wrl/client.h>
#include "base/memory/weak_ptr.h"
namespace gfx {
class Rect;
}
namespace views {
class FullscreenHandler {
public:
FullscreenHandler();
FullscreenHandler(const FullscreenHandler&) = delete;
FullscreenHandler& operator=(const FullscreenHandler&) = delete;
~FullscreenHandler();
void set_hwnd(HWND hwnd) { hwnd_ = hwnd; }
// 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.
void SetFullscreen(bool fullscreen, int64_t target_display_id);
// Informs the taskbar whether the window is a fullscreen window.
void MarkFullscreen(bool fullscreen);
gfx::Rect GetRestoreBounds() const;
bool fullscreen() const { return fullscreen_; }
private:
// Information saved before going into fullscreen mode, used to restore the
// window afterwards.
struct SavedWindowInfo {
LONG style;
LONG ex_style;
RECT rect;
int dpi;
HMONITOR monitor;
MONITORINFO monitor_info;
};
void ProcessFullscreen(bool fullscreen, int64_t target_display_id);
HWND hwnd_ = nullptr;
bool fullscreen_ = false;
// Saved window information from before entering fullscreen mode.
// TODO(beng): move to private once GetRestoredBounds() moves onto Widget.
SavedWindowInfo saved_window_info_;
// Used to mark a window as fullscreen.
Microsoft::WRL::ComPtr<ITaskbarList2> task_bar_list_;
base::WeakPtrFactory<FullscreenHandler> weak_ptr_factory_{this};
};
} // namespace views
#endif // UI_VIEWS_WIN_FULLSCREEN_HANDLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/win/fullscreen_handler.h | C++ | unknown | 1,921 |
// 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/win/hwnd_message_handler.h"
#include <dwmapi.h>
#include <oleacc.h>
#include <shellapi.h>
#include <tchar.h>
#include <wrl/client.h>
#include <utility>
#include "base/auto_reset.h"
#include "base/debug/gdi_debug_util_win.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/ranges/algorithm.h"
#include "base/strings/string_util_win.h"
#include "base/task/current_thread.h"
#include "base/task/single_thread_task_runner.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "base/win/dark_mode_support.h"
#include "base/win/scoped_gdi_object.h"
#include "base/win/win_util.h"
#include "services/tracing/public/cpp/perfetto/macros.h"
#include "third_party/perfetto/protos/perfetto/trace/track_event/chrome_window_handle_event_info.pbzero.h"
#include "third_party/skia/include/core/SkPath.h"
#include "ui/accessibility/accessibility_switches.h"
#include "ui/accessibility/platform/ax_fragment_root_win.h"
#include "ui/accessibility/platform/ax_platform_node_win.h"
#include "ui/accessibility/platform/ax_system_caret_win.h"
#include "ui/base/ime/text_input_client.h"
#include "ui/base/ime/text_input_type.h"
#include "ui/base/ui_base_features.h"
#include "ui/base/view_prop.h"
#include "ui/base/win/hwnd_metrics.h"
#include "ui/base/win/internal_constants.h"
#include "ui/base/win/lock_state.h"
#include "ui/base/win/mouse_wheel_util.h"
#include "ui/base/win/session_change_observer.h"
#include "ui/base/win/touch_input.h"
#include "ui/base/win/win_cursor.h"
#include "ui/display/types/display_constants.h"
#include "ui/display/win/dpi.h"
#include "ui/display/win/screen_win.h"
#include "ui/events/event.h"
#include "ui/events/event_constants.h"
#include "ui/events/event_utils.h"
#include "ui/events/keycodes/keyboard_code_conversion_win.h"
#include "ui/events/types/event_type.h"
#include "ui/events/win/system_event_state_lookup.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/geometry/resize_utils.h"
#include "ui/gfx/icon_util.h"
#include "ui/gfx/path_win.h"
#include "ui/gfx/win/hwnd_util.h"
#include "ui/gfx/win/rendering_window_manager.h"
#include "ui/latency/latency_info.h"
#include "ui/native_theme/native_theme_win.h"
#include "ui/views/views_delegate.h"
#include "ui/views/widget/widget_hwnd_utils.h"
#include "ui/views/win/fullscreen_handler.h"
#include "ui/views/win/hwnd_message_handler_delegate.h"
#include "ui/views/win/hwnd_util.h"
#include "ui/views/win/scoped_fullscreen_visibility.h"
namespace views {
namespace {
// MoveLoopMouseWatcher is used to determine if the user canceled or completed a
// move. win32 doesn't appear to offer a way to determine the result of a move,
// so we install hooks to determine if we got a mouse up and assume the move
// completed.
class MoveLoopMouseWatcher {
public:
MoveLoopMouseWatcher(HWNDMessageHandler* host, bool hide_on_escape);
MoveLoopMouseWatcher(const MoveLoopMouseWatcher&) = delete;
MoveLoopMouseWatcher& operator=(const MoveLoopMouseWatcher&) = delete;
~MoveLoopMouseWatcher();
// Unhooks the MoveLoopMouseWatcher instance associated with `host`, if any.
static void UnhookForHost(HWNDMessageHandler* host);
// Returns true if the mouse is up, or if we couldn't install the hook.
bool got_mouse_up() const { return got_mouse_up_; }
private:
// Instance that owns the hook. We only allow one instance to hook the mouse
// at a time.
static MoveLoopMouseWatcher* instance_;
// Key and mouse callbacks from the hook.
static LRESULT CALLBACK MouseHook(int n_code, WPARAM w_param, LPARAM l_param);
static LRESULT CALLBACK KeyHook(int n_code, WPARAM w_param, LPARAM l_param);
void Unhook();
// HWNDMessageHandler that created us.
raw_ptr<HWNDMessageHandler, DanglingUntriaged> host_;
// Should the window be hidden when escape is pressed?
const bool hide_on_escape_;
// Did we get a mouse up?
bool got_mouse_up_ = false;
// Hook identifiers.
HHOOK mouse_hook_ = nullptr;
HHOOK key_hook_ = nullptr;
};
// static
MoveLoopMouseWatcher* MoveLoopMouseWatcher::instance_ = nullptr;
MoveLoopMouseWatcher::MoveLoopMouseWatcher(HWNDMessageHandler* host,
bool hide_on_escape)
: host_(host), hide_on_escape_(hide_on_escape) {
// Only one instance can be active at a time.
if (instance_)
instance_->Unhook();
mouse_hook_ =
SetWindowsHookEx(WH_MOUSE, &MouseHook, nullptr, GetCurrentThreadId());
if (mouse_hook_) {
instance_ = this;
// We don't care if setting the key hook succeeded.
key_hook_ =
SetWindowsHookEx(WH_KEYBOARD, &KeyHook, nullptr, GetCurrentThreadId());
}
if (instance_ != this) {
// Failed installation. Assume we got a mouse up in this case, otherwise
// we'll think all drags were canceled.
got_mouse_up_ = true;
}
}
MoveLoopMouseWatcher::~MoveLoopMouseWatcher() {
Unhook();
}
// static
void MoveLoopMouseWatcher::UnhookForHost(HWNDMessageHandler* host) {
if (instance_ && instance_->host_ == host)
instance_->Unhook();
}
void MoveLoopMouseWatcher::Unhook() {
if (instance_ != this)
return;
DCHECK(mouse_hook_);
UnhookWindowsHookEx(mouse_hook_);
if (key_hook_)
UnhookWindowsHookEx(key_hook_);
key_hook_ = nullptr;
mouse_hook_ = nullptr;
instance_ = nullptr;
}
// static
LRESULT CALLBACK MoveLoopMouseWatcher::MouseHook(int n_code,
WPARAM w_param,
LPARAM l_param) {
DCHECK(instance_);
if (n_code == HC_ACTION && w_param == WM_LBUTTONUP)
instance_->got_mouse_up_ = true;
return CallNextHookEx(instance_->mouse_hook_, n_code, w_param, l_param);
}
// static
LRESULT CALLBACK MoveLoopMouseWatcher::KeyHook(int n_code,
WPARAM w_param,
LPARAM l_param) {
if (n_code == HC_ACTION && w_param == VK_ESCAPE) {
int value = TRUE;
DwmSetWindowAttribute(instance_->host_->hwnd(),
DWMWA_TRANSITIONS_FORCEDISABLED, &value,
sizeof(value));
if (instance_->hide_on_escape_)
instance_->host_->Hide();
}
return CallNextHookEx(instance_->key_hook_, n_code, w_param, l_param);
}
// Called from OnNCActivate.
BOOL CALLBACK EnumChildWindowsForRedraw(HWND hwnd, LPARAM lparam) {
DWORD process_id;
GetWindowThreadProcessId(hwnd, &process_id);
UINT flags = RDW_INVALIDATE | RDW_NOCHILDREN | RDW_FRAME;
if (process_id == GetCurrentProcessId())
flags |= RDW_UPDATENOW;
RedrawWindow(hwnd, nullptr, nullptr, flags);
return TRUE;
}
bool GetMonitorAndRects(const RECT& rect,
HMONITOR* monitor,
gfx::Rect* monitor_rect,
gfx::Rect* work_area) {
DCHECK(monitor);
DCHECK(monitor_rect);
DCHECK(work_area);
*monitor = MonitorFromRect(&rect, MONITOR_DEFAULTTONULL);
if (!*monitor)
return false;
MONITORINFO monitor_info = {0};
monitor_info.cbSize = sizeof(monitor_info);
GetMonitorInfo(*monitor, &monitor_info);
*monitor_rect = gfx::Rect(monitor_info.rcMonitor);
*work_area = gfx::Rect(monitor_info.rcWork);
return true;
}
// Enables or disables the menu item for the specified command and menu.
void EnableMenuItemByCommand(HMENU menu, UINT command, bool enabled) {
UINT flags = MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_DISABLED | MF_GRAYED);
EnableMenuItem(menu, command, flags);
}
// The thickness of an auto-hide taskbar in pixels.
constexpr int kAutoHideTaskbarThicknessPx = 2;
bool IsTopLevelWindow(HWND window) {
LONG style = ::GetWindowLong(window, GWL_STYLE);
if (!(style & WS_CHILD))
return true;
HWND parent = ::GetParent(window);
return !parent || (parent == ::GetDesktopWindow());
}
ui::EventType GetTouchEventType(POINTER_FLAGS pointer_flags) {
if (pointer_flags & POINTER_FLAG_DOWN)
return ui::ET_TOUCH_PRESSED;
if (pointer_flags & POINTER_FLAG_UPDATE)
return ui::ET_TOUCH_MOVED;
if (pointer_flags & POINTER_FLAG_UP)
return ui::ET_TOUCH_RELEASED;
return ui::ET_TOUCH_MOVED;
}
bool IsHitTestOnResizeHandle(LRESULT hittest) {
return hittest == HTRIGHT || hittest == HTLEFT || hittest == HTTOP ||
hittest == HTBOTTOM || hittest == HTTOPLEFT || hittest == HTTOPRIGHT ||
hittest == HTBOTTOMLEFT || hittest == HTBOTTOMRIGHT;
}
// Convert |param| to the gfx::ResizeEdge used in gfx::SizeRectToAspectRatio().
gfx::ResizeEdge GetWindowResizeEdge(UINT param) {
switch (param) {
case WMSZ_BOTTOM:
return gfx::ResizeEdge::kBottom;
case WMSZ_TOP:
return gfx::ResizeEdge::kTop;
case WMSZ_LEFT:
return gfx::ResizeEdge::kLeft;
case WMSZ_RIGHT:
return gfx::ResizeEdge::kRight;
case WMSZ_TOPLEFT:
return gfx::ResizeEdge::kTopLeft;
case WMSZ_TOPRIGHT:
return gfx::ResizeEdge::kTopRight;
case WMSZ_BOTTOMLEFT:
return gfx::ResizeEdge::kBottomLeft;
case WMSZ_BOTTOMRIGHT:
return gfx::ResizeEdge::kBottomRight;
default:
NOTREACHED_NORETURN();
}
}
int GetFlagsFromRawInputMessage(RAWINPUT* input) {
int flags = ui::EF_NONE;
if (input->data.mouse.usButtonFlags & RI_MOUSE_BUTTON_1_DOWN)
flags |= ui::EF_LEFT_MOUSE_BUTTON;
if (input->data.mouse.usButtonFlags & RI_MOUSE_BUTTON_2_DOWN)
flags |= ui::EF_RIGHT_MOUSE_BUTTON;
if (input->data.mouse.usButtonFlags & RI_MOUSE_BUTTON_3_DOWN)
flags |= ui::EF_MIDDLE_MOUSE_BUTTON;
if (input->data.mouse.usButtonFlags & RI_MOUSE_BUTTON_4_DOWN)
flags |= ui::EF_BACK_MOUSE_BUTTON;
if (input->data.mouse.usButtonFlags & RI_MOUSE_BUTTON_5_DOWN)
flags |= ui::EF_FORWARD_MOUSE_BUTTON;
return ui::GetModifiersFromKeyState() | flags;
}
constexpr auto kTouchDownContextResetTimeout = base::Milliseconds(500);
// Windows does not flag synthesized mouse messages from touch or pen in all
// cases. This causes us grief as we don't want to process touch and mouse
// messages concurrently. Hack as per msdn is to check if the time difference
// between the touch/pen message and the mouse move is within 500 ms and at the
// same location as the cursor.
constexpr int kSynthesizedMouseMessagesTimeDifference = 500;
// This is used in headless mode where we have to manually scale window
// bounds because we cannot rely on the platform window size since it gets
// clamped to the monitor work area.
gfx::Rect ScaleWindowBoundsMaybe(HWND hwnd, const gfx::Rect& bounds) {
const float scale = display::win::ScreenWin::GetScaleFactorForHWND(hwnd);
if (scale > 1.0) {
gfx::RectF scaled_bounds(bounds);
scaled_bounds.Scale(scale);
return gfx::ToEnclosingRect(scaled_bounds);
}
return bounds;
}
} // namespace
// A scoping class that prevents a window from being able to redraw in response
// to invalidations that may occur within it for the lifetime of the object.
//
// Why would we want such a thing? Well, it turns out Windows has some
// "unorthodox" behavior when it comes to painting its non-client areas.
// Occasionally, Windows will paint portions of the default non-client area
// right over the top of the custom frame. This is not simply fixed by handling
// WM_NCPAINT/WM_PAINT, with some investigation it turns out that this
// rendering is being done *inside* the default implementation of some message
// handlers and functions:
// . WM_SETTEXT
// . WM_SETICON
// . WM_NCLBUTTONDOWN
// . EnableMenuItem, called from our WM_INITMENU handler
// The solution is to handle these messages and call DefWindowProc ourselves,
// but prevent the window from being able to update itself for the duration of
// the call. We do this with this class, which automatically calls its
// associated Window's lock and unlock functions as it is created and destroyed.
// See documentation in those methods for the technique used.
//
// The lock only has an effect if the window was visible upon lock creation, as
// it doesn't guard against direct visiblility changes, and multiple locks may
// exist simultaneously to handle certain nested Windows messages.
//
// This lock is disabled when DirectComposition is used and there's a child
// rendering window, as the WS_CLIPCHILDREN on the parent window should
// prevent the glitched rendering and making the window contents non-visible
// can cause a them to disappear for a frame.
//
// We normally skip locked updates when Aero is on for two reasons:
// 1. Because it isn't necessary. However, for windows without WS_CAPTION a
// close button may still be drawn, so the resize lock remains enabled for
// them. See http://crrev.com/130323
// 2. Because toggling the WS_VISIBLE flag may occur while the GPU process is
// attempting to present a child window's backbuffer onscreen. When these
// two actions race with one another, the child window will either flicker
// or will simply stop updating entirely.
//
// IMPORTANT: Do not use this scoping object for large scopes or periods of
// time! IT WILL PREVENT THE WINDOW FROM BEING REDRAWN! (duh).
//
// I would love to hear Raymond Chen's explanation for all this. And maybe a
// list of other messages that this applies to ;-)
class HWNDMessageHandler::ScopedRedrawLock {
public:
explicit ScopedRedrawLock(HWNDMessageHandler* owner)
: owner_(owner),
hwnd_(owner_->hwnd()),
should_lock_(owner_->IsVisible() && !owner->HasChildRenderingWindow() &&
::IsWindow(hwnd_) && !owner_->IsHeadless() &&
(!(GetWindowLong(hwnd_, GWL_STYLE) & WS_CAPTION))) {
if (should_lock_)
owner_->LockUpdates();
}
ScopedRedrawLock(const ScopedRedrawLock&) = delete;
ScopedRedrawLock& operator=(const ScopedRedrawLock&) = delete;
~ScopedRedrawLock() {
if (!cancel_unlock_ && should_lock_ && ::IsWindow(hwnd_))
owner_->UnlockUpdates();
}
// Cancel the unlock operation, call this if the Widget is being destroyed.
void CancelUnlockOperation() { cancel_unlock_ = true; }
private:
// The owner having its style changed.
raw_ptr<HWNDMessageHandler> owner_;
// The owner's HWND, cached to avoid action after window destruction.
HWND hwnd_;
// A flag indicating that the unlock operation was canceled.
bool cancel_unlock_ = false;
// If false, don't use redraw lock.
const bool should_lock_;
};
// static HWNDMessageHandler member initialization.
base::LazyInstance<HWNDMessageHandler::FullscreenWindowMonitorMap>::
DestructorAtExit HWNDMessageHandler::fullscreen_monitor_map_ =
LAZY_INSTANCE_INITIALIZER;
////////////////////////////////////////////////////////////////////////////////
// HWNDMessageHandler, public:
LONG HWNDMessageHandler::last_touch_or_pen_message_time_ = 0;
bool HWNDMessageHandler::is_pen_active_in_client_area_ = false;
HWNDMessageHandler::HWNDMessageHandler(HWNDMessageHandlerDelegate* delegate,
const std::string& debugging_id)
: WindowImpl(debugging_id),
delegate_(delegate),
fullscreen_handler_(new FullscreenHandler),
waiting_for_close_now_(false),
use_system_default_icon_(false),
restored_enabled_(false),
current_cursor_(base::MakeRefCounted<ui::WinCursor>()),
dpi_(0),
called_enable_non_client_dpi_scaling_(false),
active_mouse_tracking_flags_(0),
is_right_mouse_pressed_on_caption_(false),
lock_updates_count_(0),
ignore_window_pos_changes_(false),
last_monitor_(nullptr),
is_first_nccalc_(true),
menu_depth_(0),
id_generator_(0),
pen_processor_(&id_generator_, true),
touch_down_contexts_(0),
last_mouse_hwheel_time_(0),
dwm_transition_desired_(false),
sent_window_size_changing_(false),
did_return_uia_object_(false),
left_button_down_on_caption_(false),
background_fullscreen_hack_(false),
pointer_events_for_touch_(::features::IsUsingWMPointerForTouch()) {}
HWNDMessageHandler::~HWNDMessageHandler() {
// Unhook MoveLoopMouseWatcher, to prevent call backs to this after deletion.
MoveLoopMouseWatcher::UnhookForHost(this);
// Clear pointer to this in `hwnd()`'s user data, to prevent installed hooks
// from calling back into this after deletion.
ClearUserData();
}
void HWNDMessageHandler::Init(HWND parent,
const gfx::Rect& bounds,
bool headless_mode) {
TRACE_EVENT0("views", "HWNDMessageHandler::Init");
GetMonitorAndRects(bounds.ToRECT(), &last_monitor_, &last_monitor_rect_,
&last_work_area_);
initial_bounds_valid_ = !bounds.IsEmpty();
// Provide the headless mode window state container.
if (headless_mode) {
headless_mode_window_ = absl::make_optional<HeadlessModeWindow>();
}
// Create the window.
WindowImpl::Init(parent, bounds);
// In headless mode remember the expected window bounds possibly adjusted
// according to the scale factor.
if (headless_mode) {
if (initial_bounds_valid_) {
SetHeadlessWindowBounds(bounds);
} else {
// If initial window bounds were not provided, use the newly created
// platform window size or fall back to the default headless window size
// as the last resort.
RECT window_rect;
if (GetWindowRect(hwnd(), &window_rect)) {
SetHeadlessWindowBounds(gfx::Rect(window_rect));
} else {
// Even if the window rectangle cannot be retrieved, there is still a
// chance that ScreenWin::GetScaleFactorForHWND() will be able to figure
// out the scale factor.
constexpr gfx::Rect kDefaultHeadlessBounds(800, 600);
SetHeadlessWindowBounds(
ScaleWindowBoundsMaybe(hwnd(), kDefaultHeadlessBounds));
}
}
}
if (!called_enable_non_client_dpi_scaling_ && delegate_->HasFrame()) {
// Derived signature; not available in headers.
// This call gets Windows to scale the non-client area when
// WM_DPICHANGED is fired.
using EnableChildWindowDpiMessagePtr = LRESULT(WINAPI*)(HWND, BOOL);
static const auto enable_child_window_dpi_message_func =
reinterpret_cast<EnableChildWindowDpiMessagePtr>(
base::win::GetUser32FunctionPointer("EnableChildWindowDpiMessage"));
if (enable_child_window_dpi_message_func)
enable_child_window_dpi_message_func(hwnd(), TRUE);
}
prop_window_target_ = std::make_unique<ui::ViewProp>(
hwnd(), ui::WindowEventTarget::kWin32InputEventTarget,
static_cast<ui::WindowEventTarget*>(this));
DCHECK(delegate_->GetHWNDMessageDelegateInputMethod());
observation_.Observe(delegate_->GetHWNDMessageDelegateInputMethod());
// The usual way for UI Automation to obtain a fragment root is through
// WM_GETOBJECT. However, if there's a relation such as "Controller For"
// between element A in one window and element B in another window, UIA might
// call element A to discover the relation, receive a pointer to element B,
// then ask element B for its fragment root, without having sent WM_GETOBJECT
// to element B's window.
// So we create the fragment root now to ensure it's ready if asked for.
if (::switches::IsExperimentalAccessibilityPlatformUIAEnabled())
ax_fragment_root_ = std::make_unique<ui::AXFragmentRootWin>(hwnd(), this);
// Disable pen flicks (http://crbug.com/506977)
base::win::DisableFlicks(hwnd());
}
void HWNDMessageHandler::InitModalType(ui::ModalType modal_type) {
if (modal_type == ui::MODAL_TYPE_NONE)
return;
// We implement modality by crawling up the hierarchy of windows starting
// at the owner, disabling all of them so that they don't receive input
// messages.
HWND start = ::GetWindow(hwnd(), GW_OWNER);
while (start) {
::EnableWindow(start, FALSE);
start = ::GetParent(start);
}
}
void HWNDMessageHandler::Close() {
if (!IsWindow(hwnd()))
return; // No need to do anything.
// Let's hide ourselves right away.
Hide();
// Modal dialog windows disable their owner windows; re-enable them now so
// they can activate as foreground windows upon this window's destruction.
RestoreEnabledIfNecessary();
// Re-enable flicks which removes the window property.
base::win::EnableFlicks(hwnd());
if (!waiting_for_close_now_) {
// And we delay the close so that if we are called from an ATL callback,
// we don't destroy the window before the callback returned (as the caller
// may delete ourselves on destroy and the ATL callback would still
// dereference us when the callback returns).
waiting_for_close_now_ = true;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&HWNDMessageHandler::CloseNow,
msg_handler_weak_factory_.GetWeakPtr()));
}
}
void HWNDMessageHandler::CloseNow() {
// We may already have been destroyed if the selection resulted in a tab
// switch which will have reactivated the browser window and closed us, so
// we need to check to see if we're still a window before trying to destroy
// ourself.
waiting_for_close_now_ = false;
if (IsWindow(hwnd()))
DestroyWindow(hwnd());
}
gfx::Rect HWNDMessageHandler::GetWindowBoundsInScreen() const {
// In headless mode return the expected window rectangle set in Init() and
// updated in SetBounds() and SetSize().
if (IsHeadless()) {
return headless_mode_window_->bounds;
}
RECT r;
GetWindowRect(hwnd(), &r);
return gfx::Rect(r);
}
gfx::Rect HWNDMessageHandler::GetClientAreaBoundsInScreen() const {
// In headless mode calculate the client rectangle using the difference
// between platform window and client rectangles.
if (IsHeadless()) {
gfx::Insets client_insets;
if (!GetClientAreaInsets(&client_insets, last_monitor_)) {
RECT window_rect;
if (!GetWindowRect(hwnd(), &window_rect)) {
return gfx::Rect();
}
RECT client_rect;
if (!GetClientRect(hwnd(), &client_rect)) {
return gfx::Rect(window_rect);
}
client_insets.set_left(client_rect.left - window_rect.left);
client_insets.set_right(window_rect.right - client_rect.right);
client_insets.set_top(client_rect.top - window_rect.top);
client_insets.set_bottom(window_rect.bottom - client_rect.bottom);
}
gfx::Rect bounds = headless_mode_window_->bounds;
bounds.Inset(client_insets);
if (bounds.IsEmpty()) {
return headless_mode_window_->bounds;
}
return bounds;
}
RECT r;
GetClientRect(hwnd(), &r);
POINT point = {r.left, r.top};
ClientToScreen(hwnd(), &point);
return gfx::Rect(point.x, point.y, r.right - r.left, r.bottom - r.top);
}
gfx::Rect HWNDMessageHandler::GetRestoredBounds() const {
// Headless mode window never goes fullscreen, so just return the expected
// bounds rectangle here.
if (IsHeadless()) {
return headless_mode_window_->bounds;
}
// If we're in fullscreen mode, we've changed the normal bounds to the monitor
// rect, so return the saved bounds instead.
if (IsFullscreen())
return fullscreen_handler_->GetRestoreBounds();
gfx::Rect bounds;
GetWindowPlacement(&bounds, nullptr);
return bounds;
}
gfx::Rect HWNDMessageHandler::GetClientAreaBounds() const {
if (IsMinimized())
return gfx::Rect();
if (delegate_->WidgetSizeIsClientSize())
return GetClientAreaBoundsInScreen();
return GetWindowBoundsInScreen();
}
void HWNDMessageHandler::GetWindowPlacement(
gfx::Rect* bounds,
ui::WindowShowState* show_state) const {
WINDOWPLACEMENT wp;
wp.length = sizeof(wp);
bool succeeded = !!::GetWindowPlacement(hwnd(), &wp);
DCHECK(succeeded);
if (bounds != nullptr) {
if (wp.showCmd == SW_SHOWNORMAL) {
// GetWindowPlacement can return misleading position if a normalized
// window was resized using Aero Snap feature (see comment 9 in bug
// 36421). As a workaround, using GetWindowRect for normalized windows.
succeeded = GetWindowRect(hwnd(), &wp.rcNormalPosition) != 0;
DCHECK(succeeded);
*bounds = gfx::Rect(wp.rcNormalPosition);
} else {
MONITORINFO mi;
mi.cbSize = sizeof(mi);
succeeded =
GetMonitorInfo(MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST),
&mi) != 0;
DCHECK(succeeded);
*bounds = gfx::Rect(wp.rcNormalPosition);
// Convert normal position from workarea coordinates to screen
// coordinates.
bounds->Offset(mi.rcWork.left - mi.rcMonitor.left,
mi.rcWork.top - mi.rcMonitor.top);
}
}
if (show_state) {
if (wp.showCmd == SW_SHOWMAXIMIZED)
*show_state = ui::SHOW_STATE_MAXIMIZED;
else if (wp.showCmd == SW_SHOWMINIMIZED)
*show_state = ui::SHOW_STATE_MINIMIZED;
else
*show_state = ui::SHOW_STATE_NORMAL;
}
}
void HWNDMessageHandler::SetBounds(const gfx::Rect& bounds_in_pixels,
bool force_size_changed) {
background_fullscreen_hack_ = false;
SetBoundsInternal(bounds_in_pixels, force_size_changed);
}
void HWNDMessageHandler::SetDwmFrameExtension(DwmFrameState state) {
if (!delegate_->HasFrame() && !is_translucent_) {
MARGINS m = {0, 0, 0, 0};
if (state == DwmFrameState::kOn && !IsMaximized())
m = {0, 0, 1, 0};
DwmExtendFrameIntoClientArea(hwnd(), &m);
}
}
void HWNDMessageHandler::SetSize(const gfx::Size& size) {
// In headless mode update the expected window size and pretend the platform
// window size was updated.
if (IsHeadless()) {
bool size_changed = headless_mode_window_->bounds.size() != size;
gfx::Rect bounds = headless_mode_window_->bounds;
bounds.set_size(size);
SetHeadlessWindowBounds(bounds);
if (size_changed) {
delegate_->HandleClientSizeChanged(GetClientAreaBounds().size());
}
return;
}
SetWindowPos(hwnd(), nullptr, 0, 0, size.width(), size.height(),
SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE);
}
void HWNDMessageHandler::CenterWindow(const gfx::Size& size) {
HWND parent = GetParent(hwnd());
if (!IsWindow(hwnd()))
parent = ::GetWindow(hwnd(), GW_OWNER);
gfx::CenterAndSizeWindow(parent, hwnd(), size);
}
void HWNDMessageHandler::SetRegion(HRGN region) {
custom_window_region_.reset(region);
ResetWindowRegion(true, true);
}
void HWNDMessageHandler::StackAbove(HWND other_hwnd) {
// Windows API allows to stack behind another windows only.
DCHECK(other_hwnd);
HWND next_window = GetNextWindow(other_hwnd, GW_HWNDPREV);
SetWindowPos(hwnd(), next_window ? next_window : HWND_TOP, 0, 0, 0, 0,
SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
}
void HWNDMessageHandler::StackAtTop() {
SetWindowPos(hwnd(), HWND_TOP, 0, 0, 0, 0,
SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
}
void HWNDMessageHandler::Show(ui::WindowShowState show_state,
const gfx::Rect& pixel_restore_bounds) {
TRACE_EVENT0("views", "HWNDMessageHandler::Show");
// In headless mode the platform window is always hidden, so instead of
// showing it just maintain a local flag to track the expected headless
// window visibility state and explicitly activate window just like
// platform window manager would do.
if (IsHeadless()) {
headless_mode_window_->visibility_state = true;
if (show_state != ui::SHOW_STATE_INACTIVE) {
Activate();
}
return;
}
int native_show_state;
if (show_state == ui::SHOW_STATE_MAXIMIZED &&
!pixel_restore_bounds.IsEmpty()) {
WINDOWPLACEMENT placement = {0};
placement.length = sizeof(WINDOWPLACEMENT);
placement.showCmd = SW_SHOWMAXIMIZED;
placement.rcNormalPosition = pixel_restore_bounds.ToRECT();
SetWindowPlacement(hwnd(), &placement);
native_show_state = SW_SHOWMAXIMIZED;
} else {
const bool is_maximized = IsMaximized();
// Use SW_SHOW/SW_SHOWNA instead of SW_SHOWNORMAL/SW_SHOWNOACTIVATE so that
// the window is not restored to its original position if it is maximized.
// This could be used unconditionally for ui::SHOW_STATE_INACTIVE, but
// cross-platform behavior when showing a minimized window is inconsistent,
// some platforms restore the position, some do not. See crbug.com/1296710
switch (show_state) {
case ui::SHOW_STATE_INACTIVE:
native_show_state = is_maximized ? SW_SHOWNA : SW_SHOWNOACTIVATE;
break;
case ui::SHOW_STATE_MAXIMIZED:
native_show_state = SW_SHOWMAXIMIZED;
break;
case ui::SHOW_STATE_MINIMIZED:
native_show_state = SW_SHOWMINIMIZED;
break;
case ui::SHOW_STATE_NORMAL:
if ((GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TRANSPARENT) ||
(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)) {
native_show_state = is_maximized ? SW_SHOWNA : SW_SHOWNOACTIVATE;
} else {
native_show_state = is_maximized ? SW_SHOW : SW_SHOWNORMAL;
}
break;
case ui::SHOW_STATE_FULLSCREEN:
native_show_state = SW_SHOWNORMAL;
SetFullscreen(true, display::kInvalidDisplayId);
break;
default:
native_show_state = delegate_->GetInitialShowState();
break;
}
ShowWindow(hwnd(), native_show_state);
// When launched from certain programs like bash and Windows Live
// Messenger, show_state is set to SW_HIDE, so we need to correct that
// condition. We don't just change show_state to SW_SHOWNORMAL because
// MSDN says we must always first call ShowWindow with the specified
// value from STARTUPINFO, otherwise all future ShowWindow calls will be
// ignored (!!#@@#!). Instead, we call ShowWindow again in this case.
if (native_show_state == SW_HIDE) {
native_show_state = SW_SHOWNORMAL;
ShowWindow(hwnd(), native_show_state);
}
}
// We need to explicitly activate the window if we've been shown with a state
// that should activate, because if we're opened from a desktop shortcut while
// an existing window is already running it doesn't seem to be enough to use
// one of these flags to activate the window.
if (native_show_state == SW_SHOWNORMAL ||
native_show_state == SW_SHOWMAXIMIZED)
Activate();
if (!delegate_->HandleInitialFocus(show_state))
SetInitialFocus();
}
void HWNDMessageHandler::Hide() {
// In headless mode the platform window is always hidden, so instead of
// hiding it just maintain a local flag to track the expected headless
// window visibility state.
if (IsHeadless()) {
headless_mode_window_->visibility_state = false;
return;
}
if (IsWindow(hwnd())) {
// NOTE: Be careful not to activate any windows here (for example, calling
// ShowWindow(SW_HIDE) will automatically activate another window). This
// code can be called while a window is being deactivated, and activating
// another window will screw up the activation that is already in progress.
SetWindowPos(hwnd(), nullptr, 0, 0, 0, 0,
SWP_HIDEWINDOW | SWP_NOACTIVATE | SWP_NOMOVE |
SWP_NOREPOSITION | SWP_NOSIZE | SWP_NOZORDER);
}
}
void HWNDMessageHandler::Maximize() {
if (IsHeadless()) {
headless_mode_window_->minmax_state = HeadlessModeWindow::kMaximized;
return;
}
ExecuteSystemMenuCommand(SC_MAXIMIZE);
}
void HWNDMessageHandler::Minimize() {
if (IsHeadless()) {
headless_mode_window_->minmax_state = HeadlessModeWindow::kMinimized;
return;
}
ExecuteSystemMenuCommand(SC_MINIMIZE);
delegate_->HandleNativeBlur(nullptr);
}
void HWNDMessageHandler::Restore() {
if (IsHeadless()) {
headless_mode_window_->minmax_state = HeadlessModeWindow::kNormal;
return;
}
ExecuteSystemMenuCommand(SC_RESTORE);
}
void HWNDMessageHandler::Activate() {
// In headless mode the platform window is always hidden, so instead of
// activating it just maintain a local flag to track the expected headless
// window activation state.
if (IsHeadless()) {
if (!headless_mode_window_->active_state) {
headless_mode_window_->active_state = true;
if (delegate_->CanActivate() && IsTopLevelWindow(hwnd())) {
delegate_->HandleActivationChanged(/*active=*/true);
}
}
return;
}
if (IsMinimized()) {
base::AutoReset<bool> restoring_activate(¬ify_restore_on_activate_,
true);
::ShowWindow(hwnd(), SW_RESTORE);
}
::SetWindowPos(hwnd(), HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
SetForegroundWindow(hwnd());
}
void HWNDMessageHandler::Deactivate() {
if (IsHeadless()) {
if (headless_mode_window_->active_state) {
headless_mode_window_->active_state = false;
if (delegate_->CanActivate() && IsTopLevelWindow(hwnd())) {
delegate_->HandleActivationChanged(/*active=*/false);
}
}
return;
}
HWND next_hwnd = ::GetNextWindow(hwnd(), GW_HWNDNEXT);
while (next_hwnd) {
if (::IsWindowVisible(next_hwnd)) {
::SetForegroundWindow(next_hwnd);
return;
}
next_hwnd = ::GetNextWindow(next_hwnd, GW_HWNDNEXT);
}
}
void HWNDMessageHandler::SetAlwaysOnTop(bool on_top) {
::SetWindowPos(hwnd(), on_top ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
}
bool HWNDMessageHandler::IsVisible() const {
// In headless mode the platform window is always hidden, so instead of
// returning the actual window visibility state return the expected visibility
// state maintained by Show/Hide() calls.
return IsHeadless() ? headless_mode_window_->visibility_state
: !!::IsWindowVisible(hwnd());
}
bool HWNDMessageHandler::IsActive() const {
// In headless mode return expected activation state instead of the
// actual one. This ensures that onfocus/onblur notifications work
// as expected and no unexpected throttling occurs.
// This active state is checked via FocusManager::SetFocusedViewWithReason.
// With CEF external parent hwnd() may be a child window, whereas
// GetActiveWindow() will return the root window, so make sure that we always
// compare root windows.
return IsHeadless() ? headless_mode_window_->active_state
: GetActiveWindow() == GetAncestor(hwnd(), GA_ROOT);
}
bool HWNDMessageHandler::IsMinimized() const {
return IsHeadless() ? headless_mode_window_->IsMinimized()
: !!::IsIconic(hwnd());
}
bool HWNDMessageHandler::IsMaximized() const {
return (IsHeadless() ? headless_mode_window_->IsMaximized()
: !!::IsZoomed(hwnd())) &&
!IsFullscreen();
}
bool HWNDMessageHandler::IsFullscreen() const {
// In headless mode report the requested window state instead of the actual
// one.
return IsHeadless() ? headless_mode_window_->fullscreen_state
: fullscreen_handler_->fullscreen();
}
bool HWNDMessageHandler::IsAlwaysOnTop() const {
return (GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TOPMOST) != 0;
}
bool HWNDMessageHandler::IsHeadless() const {
return headless_mode_window_.has_value();
}
bool HWNDMessageHandler::RunMoveLoop(const gfx::Vector2d& drag_offset,
bool hide_on_escape) {
ReleaseCapture();
MoveLoopMouseWatcher watcher(this, hide_on_escape);
// In Aura, we handle touch events asynchronously. So we need to allow nested
// tasks while in windows move loop.
base::CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop allow;
SendMessage(hwnd(), WM_SYSCOMMAND, SC_MOVE | 0x0002,
static_cast<LPARAM>(GetMessagePos()));
// Windows doesn't appear to offer a way to determine whether the user
// canceled the move or not. We assume if the user released the mouse it was
// successful.
return watcher.got_mouse_up();
}
void HWNDMessageHandler::EndMoveLoop() {
SendMessage(hwnd(), WM_CANCELMODE, 0, 0);
}
void HWNDMessageHandler::SendFrameChanged() {
SetWindowPos(hwnd(), nullptr, 0, 0, 0, 0,
SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOMOVE |
SWP_NOOWNERZORDER | SWP_NOREPOSITION | SWP_NOSENDCHANGING |
SWP_NOSIZE | SWP_NOZORDER);
}
void HWNDMessageHandler::FlashFrame(bool flash) {
FLASHWINFO fwi;
fwi.cbSize = sizeof(fwi);
fwi.hwnd = hwnd();
if (flash) {
fwi.dwFlags = custom_window_region_.is_valid() ? FLASHW_TRAY : FLASHW_ALL;
fwi.uCount = 4;
fwi.dwTimeout = 0;
} else {
fwi.dwFlags = FLASHW_STOP;
}
FlashWindowEx(&fwi);
}
void HWNDMessageHandler::ClearNativeFocus() {
::SetFocus(hwnd());
}
void HWNDMessageHandler::SetCapture() {
// We may need to change this to !HasCapture() || release_capture_errno_ to
// avoid checking when the call to `::ReleaseCapture` below fails.
// Logging release_capture_errno_ will tell us if the DCHECK below is caused
// by ::ReleaseCapture failing.
DCHECK(!HasCapture()) << " release capture error = "
<< logging::SystemErrorCodeToString(
release_capture_errno_);
::SetCapture(hwnd());
}
void HWNDMessageHandler::ReleaseCapture() {
if (HasCapture() && !::ReleaseCapture())
release_capture_errno_ = ::GetLastError();
else
release_capture_errno_ = 0;
}
bool HWNDMessageHandler::HasCapture() const {
return ::GetCapture() == hwnd();
}
void HWNDMessageHandler::SetVisibilityChangedAnimationsEnabled(bool enabled) {
int dwm_value = enabled ? FALSE : TRUE;
DwmSetWindowAttribute(hwnd(), DWMWA_TRANSITIONS_FORCEDISABLED, &dwm_value,
sizeof(dwm_value));
}
bool HWNDMessageHandler::SetTitle(const std::u16string& title) {
std::wstring current_title;
auto len_with_null = static_cast<size_t>(GetWindowTextLength(hwnd())) + 1;
if (len_with_null == 1 && title.length() == 0)
return false;
if (len_with_null - 1 == title.length() &&
GetWindowText(hwnd(), base::WriteInto(¤t_title, len_with_null),
len_with_null) &&
current_title == base::AsWStringPiece(title))
return false;
SetWindowText(hwnd(), base::as_wcstr(title));
return true;
}
void HWNDMessageHandler::SetCursor(scoped_refptr<ui::WinCursor> cursor) {
DCHECK(cursor);
TRACE_EVENT1("ui,input", "HWNDMessageHandler::SetCursor", "cursor",
static_cast<const void*>(cursor->hcursor()));
::SetCursor(cursor->hcursor());
current_cursor_ = cursor;
}
void HWNDMessageHandler::FrameTypeChanged() {
needs_dwm_frame_clear_ = true;
if (!custom_window_region_.is_valid() && IsFrameSystemDrawn())
dwm_transition_desired_ = true;
if (!dwm_transition_desired_ || !IsFullscreen())
PerformDwmTransition();
}
void HWNDMessageHandler::PaintAsActiveChanged() {
if (!delegate_->HasNonClientView() || !delegate_->CanActivate() ||
!delegate_->HasFrame() ||
(delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN)) {
return;
}
DefWindowProcWithRedrawLock(WM_NCACTIVATE, delegate_->ShouldPaintAsActive(),
0);
}
void HWNDMessageHandler::SetWindowIcons(const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon) {
if (!window_icon.isNull()) {
base::win::ScopedHICON previous_icon = std::move(window_icon_);
window_icon_ = IconUtil::CreateHICONFromSkBitmap(*window_icon.bitmap());
SendMessage(hwnd(), WM_SETICON, ICON_SMALL,
reinterpret_cast<LPARAM>(window_icon_.get()));
}
if (!app_icon.isNull()) {
base::win::ScopedHICON previous_icon = std::move(app_icon_);
app_icon_ = IconUtil::CreateHICONFromSkBitmap(*app_icon.bitmap());
SendMessage(hwnd(), WM_SETICON, ICON_BIG,
reinterpret_cast<LPARAM>(app_icon_.get()));
}
}
void HWNDMessageHandler::SetFullscreen(bool fullscreen,
int64_t target_display_id) {
// Avoid setting fullscreen mode when in headless mode, but keep track
// of the requested state for IsFullscreen() to report.
if (IsHeadless()) {
headless_mode_window_->fullscreen_state = fullscreen;
return;
}
// Erase any prior reference to this window in the fullscreen window map.
HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTOPRIMARY);
FullscreenWindowMonitorMap::iterator iter =
fullscreen_monitor_map_.Get().find(monitor);
if (iter != fullscreen_monitor_map_.Get().end())
fullscreen_monitor_map_.Get().erase(iter);
background_fullscreen_hack_ = false;
auto ref = msg_handler_weak_factory_.GetWeakPtr();
fullscreen_handler()->SetFullscreen(fullscreen, target_display_id);
if (!ref)
return;
// Add an entry in the fullscreen window map if the window is now fullscreen.
if (fullscreen) {
HMONITOR new_monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTOPRIMARY);
(fullscreen_monitor_map_.Get())[new_monitor] = this;
}
// If we are out of fullscreen and there was a pending DWM transition for the
// window, then go ahead and do it now.
if (!fullscreen && dwm_transition_desired_)
PerformDwmTransition();
}
void HWNDMessageHandler::SetAspectRatio(float aspect_ratio,
const gfx::Size& excluded_margin) {
// If the aspect ratio is not in the valid range, do nothing.
DCHECK_GT(aspect_ratio, 0.0f);
aspect_ratio_ = aspect_ratio;
// Convert to pixels.
excluded_margin_ =
display::win::ScreenWin::DIPToScreenSize(hwnd(), excluded_margin);
// When the aspect ratio is set, size the window to adhere to it. This keeps
// the same origin point as the original window.
RECT window_rect;
if (GetWindowRect(hwnd(), &window_rect)) {
gfx::Rect rect(window_rect);
SizeWindowToAspectRatio(WMSZ_BOTTOMRIGHT, &rect);
SetBoundsInternal(rect, false);
}
}
void HWNDMessageHandler::SizeConstraintsChanged() {
LONG style = GetWindowLong(hwnd(), GWL_STYLE);
// Ignore if this is not a standard window.
if (style & static_cast<LONG>(WS_POPUP | WS_CHILD))
return;
// Windows cannot have WS_THICKFRAME set if translucent.
// See CalculateWindowStylesFromInitParams().
if (delegate_->CanResize() && !is_translucent_) {
style |= WS_THICKFRAME | WS_MAXIMIZEBOX;
if (!delegate_->CanMaximize())
style &= ~WS_MAXIMIZEBOX;
} else {
style &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
}
if (delegate_->CanMinimize()) {
style |= WS_MINIMIZEBOX;
} else {
style &= ~WS_MINIMIZEBOX;
}
SetWindowLong(hwnd(), GWL_STYLE, style);
}
bool HWNDMessageHandler::HasChildRenderingWindow() {
// This can change dynamically if the system switches between GPU and
// software rendering.
return gfx::RenderingWindowManager::GetInstance()->HasValidChildWindow(
hwnd());
}
std::unique_ptr<aura::ScopedEnableUnadjustedMouseEvents>
HWNDMessageHandler::RegisterUnadjustedMouseEvent() {
std::unique_ptr<ScopedEnableUnadjustedMouseEventsWin> scoped_enable =
ScopedEnableUnadjustedMouseEventsWin::StartMonitor(this);
DCHECK(using_wm_input_);
return scoped_enable;
}
////////////////////////////////////////////////////////////////////////////////
// HWNDMessageHandler, gfx::WindowImpl overrides:
HICON HWNDMessageHandler::GetDefaultWindowIcon() const {
return use_system_default_icon_
? nullptr
: ViewsDelegate::GetInstance()->GetDefaultWindowIcon();
}
HICON HWNDMessageHandler::GetSmallWindowIcon() const {
return use_system_default_icon_
? nullptr
: ViewsDelegate::GetInstance()->GetSmallWindowIcon();
}
LRESULT HWNDMessageHandler::OnWndProc(UINT message,
WPARAM w_param,
LPARAM l_param) {
TRACE_EVENT("ui,toplevel", "HWNDMessageHandler::OnWndProc",
[&](perfetto::EventContext ctx) {
perfetto::protos::pbzero::ChromeWindowHandleEventInfo* args =
ctx.event()->set_chrome_window_handle_event_info();
args->set_message_id(message);
args->set_hwnd_ptr(
static_cast<uint64_t>(reinterpret_cast<uintptr_t>(hwnd())));
});
HWND window = hwnd();
LRESULT result = 0;
if (delegate_ && delegate_->PreHandleMSG(message, w_param, l_param, &result))
return result;
// Otherwise we handle everything else.
// NOTE: We inline ProcessWindowMessage() as 'this' may be destroyed during
// dispatch and ProcessWindowMessage() doesn't deal with that well.
const BOOL old_msg_handled = msg_handled_;
base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
const BOOL processed =
_ProcessWindowMessage(window, message, w_param, l_param, result, 0);
if (!ref)
return 0;
msg_handled_ = old_msg_handled;
if (!processed) {
result = DefWindowProc(window, message, w_param, l_param);
// DefWindowProc() may have destroyed the window and/or us in a nested
// message loop.
if (!ref || !::IsWindow(window))
return result;
}
if (delegate_) {
delegate_->PostHandleMSG(message, w_param, l_param);
if (message == WM_NCDESTROY) {
RestoreEnabledIfNecessary();
delegate_->HandleDestroyed();
}
}
if (message == WM_ACTIVATE && IsTopLevelWindow(window)) {
PostProcessActivateMessage(LOWORD(w_param), !!HIWORD(w_param),
reinterpret_cast<HWND>(l_param));
}
return result;
}
void HWNDMessageHandler::OnFocus() {}
void HWNDMessageHandler::OnBlur() {}
void HWNDMessageHandler::OnCaretBoundsChanged(
const ui::TextInputClient* client) {
if (!ax_system_caret_)
ax_system_caret_ = std::make_unique<ui::AXSystemCaretWin>(hwnd());
if (!client || client->GetTextInputType() == ui::TEXT_INPUT_TYPE_NONE) {
ax_system_caret_->Hide();
return;
}
const gfx::Rect dip_caret_bounds(client->GetCaretBounds());
gfx::Rect caret_bounds =
display::win::ScreenWin::DIPToScreenRect(hwnd(), dip_caret_bounds);
// Collapse any selection.
caret_bounds.set_width(1);
ax_system_caret_->MoveCaretTo(caret_bounds);
}
void HWNDMessageHandler::OnTextInputStateChanged(
const ui::TextInputClient* client) {
if (!client || client->GetTextInputType() == ui::TEXT_INPUT_TYPE_NONE)
OnCaretBoundsChanged(client);
}
void HWNDMessageHandler::OnInputMethodDestroyed(
const ui::InputMethod* input_method) {
DestroyAXSystemCaret();
}
LRESULT HWNDMessageHandler::HandleMouseMessage(unsigned int message,
WPARAM w_param,
LPARAM l_param,
bool* handled) {
// Don't track forwarded mouse messages. We expect the caller to track the
// mouse.
base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
LRESULT ret = HandleMouseEventInternal(message, w_param, l_param, false);
*handled = !ref.get() || msg_handled_;
return ret;
}
LRESULT HWNDMessageHandler::HandleKeyboardMessage(unsigned int message,
WPARAM w_param,
LPARAM l_param,
bool* handled) {
base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
LRESULT ret = 0;
if ((message == WM_CHAR) || (message == WM_SYSCHAR))
ret = OnImeMessages(message, w_param, l_param);
else
ret = OnKeyEvent(message, w_param, l_param);
*handled = !ref.get() || msg_handled_;
return ret;
}
LRESULT HWNDMessageHandler::HandleTouchMessage(unsigned int message,
WPARAM w_param,
LPARAM l_param,
bool* handled) {
base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
LRESULT ret = OnTouchEvent(message, w_param, l_param);
*handled = !ref.get() || msg_handled_;
return ret;
}
LRESULT HWNDMessageHandler::HandlePointerMessage(unsigned int message,
WPARAM w_param,
LPARAM l_param,
bool* handled) {
base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
LRESULT ret = OnPointerEvent(message, w_param, l_param);
*handled = !ref.get() || msg_handled_;
return ret;
}
LRESULT HWNDMessageHandler::HandleInputMessage(unsigned int message,
WPARAM w_param,
LPARAM l_param,
bool* handled) {
base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
LRESULT ret = OnInputEvent(message, w_param, l_param);
*handled = !ref.get() || msg_handled_;
return ret;
}
LRESULT HWNDMessageHandler::HandleScrollMessage(unsigned int message,
WPARAM w_param,
LPARAM l_param,
bool* handled) {
base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
LRESULT ret = OnScrollMessage(message, w_param, l_param);
*handled = !ref.get() || msg_handled_;
return ret;
}
LRESULT HWNDMessageHandler::HandleNcHitTestMessage(unsigned int message,
WPARAM w_param,
LPARAM l_param,
bool* handled) {
base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
LRESULT ret = OnNCHitTest(
gfx::Point(CR_GET_X_LPARAM(l_param), CR_GET_Y_LPARAM(l_param)));
*handled = !ref.get() || msg_handled_;
return ret;
}
void HWNDMessageHandler::HandleParentChanged() {
// If the forwarder window's parent is changed then we need to reset our
// context as we will not receive touch releases if the touch was initiated
// in the forwarder window.
touch_ids_.clear();
}
void HWNDMessageHandler::ApplyPinchZoomScale(float scale) {
POINT cursor_pos = GetCursorPos();
ScreenToClient(hwnd(), &cursor_pos);
ui::GestureEventDetails event_details(ui::ET_GESTURE_PINCH_UPDATE);
event_details.set_device_type(ui::GestureDeviceType::DEVICE_TOUCHPAD);
event_details.set_scale(scale);
ui::GestureEvent event(cursor_pos.x, cursor_pos.y, ui::EF_NONE,
base::TimeTicks::Now(), event_details);
delegate_->HandleGestureEvent(&event);
}
void HWNDMessageHandler::ApplyPinchZoomBegin() {
POINT cursor_pos = GetCursorPos();
ScreenToClient(hwnd(), &cursor_pos);
ui::GestureEventDetails event_details(ui::ET_GESTURE_PINCH_BEGIN);
event_details.set_device_type(ui::GestureDeviceType::DEVICE_TOUCHPAD);
ui::GestureEvent event(cursor_pos.x, cursor_pos.y, ui::EF_NONE,
base::TimeTicks::Now(), event_details);
delegate_->HandleGestureEvent(&event);
}
void HWNDMessageHandler::ApplyPinchZoomEnd() {
POINT cursor_pos = GetCursorPos();
ScreenToClient(hwnd(), &cursor_pos);
ui::GestureEventDetails event_details(ui::ET_GESTURE_PINCH_END);
event_details.set_device_type(ui::GestureDeviceType::DEVICE_TOUCHPAD);
ui::GestureEvent event(cursor_pos.x, cursor_pos.y, ui::EF_NONE,
base::TimeTicks::Now(), event_details);
delegate_->HandleGestureEvent(&event);
}
void HWNDMessageHandler::ApplyPanGestureEvent(
int scroll_x,
int scroll_y,
ui::EventMomentumPhase momentum_phase,
ui::ScrollEventPhase phase) {
gfx::Vector2d offset{scroll_x, scroll_y};
POINT root_location = GetCursorPos();
POINT location = {root_location.x, root_location.y};
ScreenToClient(hwnd(), &location);
gfx::Point cursor_location(location);
gfx::Point cursor_root_location(root_location);
int modifiers = ui::GetModifiersFromKeyState();
ui::ScrollEvent event(ui::ET_SCROLL, cursor_location, ui::EventTimeForNow(),
modifiers, scroll_x, scroll_y, scroll_x, scroll_y, 2,
momentum_phase, phase);
delegate_->HandleScrollEvent(&event);
}
void HWNDMessageHandler::ApplyPanGestureScroll(int scroll_x, int scroll_y) {
ApplyPanGestureEvent(scroll_x, scroll_y, ui::EventMomentumPhase::NONE,
ui::ScrollEventPhase::kUpdate);
}
void HWNDMessageHandler::ApplyPanGestureFling(int scroll_x, int scroll_y) {
ApplyPanGestureEvent(scroll_x, scroll_y,
ui::EventMomentumPhase::INERTIAL_UPDATE,
ui::ScrollEventPhase::kNone);
}
void HWNDMessageHandler::ApplyPanGestureScrollBegin(int scroll_x,
int scroll_y) {
// Phase information will be ingored in ApplyPanGestureEvent().
ApplyPanGestureEvent(scroll_x, scroll_y, ui::EventMomentumPhase::NONE,
ui::ScrollEventPhase::kBegan);
}
void HWNDMessageHandler::ApplyPanGestureScrollEnd(bool transitioning_to_pinch) {
ApplyPanGestureEvent(0, 0,
transitioning_to_pinch ? ui::EventMomentumPhase::BLOCKED
: ui::EventMomentumPhase::NONE,
ui::ScrollEventPhase::kEnd);
}
void HWNDMessageHandler::ApplyPanGestureFlingBegin() {
ApplyPanGestureEvent(0, 0, ui::EventMomentumPhase::BEGAN,
ui::ScrollEventPhase::kNone);
}
void HWNDMessageHandler::ApplyPanGestureFlingEnd() {
ApplyPanGestureEvent(0, 0, ui::EventMomentumPhase::END,
ui::ScrollEventPhase::kNone);
}
gfx::NativeViewAccessible HWNDMessageHandler::GetChildOfAXFragmentRoot() {
return delegate_->GetNativeViewAccessible();
}
gfx::NativeViewAccessible HWNDMessageHandler::GetParentOfAXFragmentRoot() {
return nullptr;
}
bool HWNDMessageHandler::IsAXFragmentRootAControlElement() {
return true;
}
////////////////////////////////////////////////////////////////////////////////
// HWNDMessageHandler, private:
int HWNDMessageHandler::GetAppbarAutohideEdges(HMONITOR monitor) {
autohide_factory_.InvalidateWeakPtrs();
return ViewsDelegate::GetInstance()->GetAppbarAutohideEdges(
monitor, base::BindOnce(&HWNDMessageHandler::OnAppbarAutohideEdgesChanged,
autohide_factory_.GetWeakPtr()));
}
void HWNDMessageHandler::OnAppbarAutohideEdgesChanged() {
// This triggers querying WM_NCCALCSIZE again.
RECT client;
GetWindowRect(hwnd(), &client);
SetWindowPos(hwnd(), nullptr, client.left, client.top,
client.right - client.left, client.bottom - client.top,
SWP_FRAMECHANGED);
}
void HWNDMessageHandler::SetInitialFocus() {
if (!(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TRANSPARENT) &&
!(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)) {
// The window does not get keyboard messages unless we focus it.
SetFocus(hwnd());
}
}
void HWNDMessageHandler::PostProcessActivateMessage(
int activation_state,
bool minimized,
HWND window_gaining_or_losing_activation) {
DCHECK(IsTopLevelWindow(hwnd()));
// Check if this is a legacy window created for screen readers.
if (::IsChild(hwnd(), window_gaining_or_losing_activation) &&
gfx::GetClassName(window_gaining_or_losing_activation) ==
std::wstring(ui::kLegacyRenderWidgetHostHwnd)) {
// In Aura, there is only one main HWND which comprises the whole browser
// window. Some screen readers however, expect every unique web content
// container (WebView) to be in its own HWND. In these cases, a dummy HWND
// with class name |Chrome_RenderWidgetHostHWND| is created for each web
// content container.
// Note that this dummy window should not interfere with focus, and instead
// delegates its accessibility implementation to the root of the
// |BrowserAccessibilityManager| tree.
return;
}
const bool active = activation_state != WA_INACTIVE && !minimized;
if (notify_restore_on_activate_) {
notify_restore_on_activate_ = false;
delegate_->HandleWindowMinimizedOrRestored(/*restored=*/true);
// Prevent OnSize() from also calling HandleWindowMinimizedOrRestored.
last_size_param_ = SIZE_RESTORED;
}
if (delegate_->CanActivate())
delegate_->HandleActivationChanged(active);
if (!::IsWindow(window_gaining_or_losing_activation))
window_gaining_or_losing_activation = ::GetForegroundWindow();
// If the window losing activation is a fullscreen window, we reduce the size
// of the window by 1px. i.e. Not fullscreen. This is to work around an
// apparent bug in the Windows taskbar where in it tracks fullscreen state on
// a per thread basis. This causes it not be a topmost window when any
// maximized window on a thread which has a fullscreen window is active. This
// affects the way these windows interact with the taskbar, they obscure it
// when maximized, autohide does not work correctly, etc.
// By reducing the size of the fullscreen window by 1px, we ensure that the
// taskbar no longer treats the window and in turn the thread as a fullscreen
// thread. This in turn ensures that maximized windows on the same thread
// don't obscure the taskbar, etc.
// Please note that this taskbar behavior only occurs if the window becoming
// active is on the same monitor as the fullscreen window.
if (!active) {
if (IsFullscreen() && ::IsWindow(window_gaining_or_losing_activation)) {
HMONITOR active_window_monitor = MonitorFromWindow(
window_gaining_or_losing_activation, MONITOR_DEFAULTTOPRIMARY);
HMONITOR fullscreen_window_monitor =
MonitorFromWindow(hwnd(), MONITOR_DEFAULTTOPRIMARY);
if (active_window_monitor == fullscreen_window_monitor)
OnBackgroundFullscreen();
}
} else if (background_fullscreen_hack_) {
// Restore the bounds of the window to fullscreen.
DCHECK(IsFullscreen());
MONITORINFO monitor_info = {sizeof(monitor_info)};
GetMonitorInfo(MonitorFromWindow(hwnd(), MONITOR_DEFAULTTOPRIMARY),
&monitor_info);
SetBoundsInternal(gfx::Rect(monitor_info.rcMonitor), false);
// Inform the taskbar that this window is now a fullscreen window so it go
// behind the window in the Z-Order. The taskbar heuristics to detect
// fullscreen windows are not reliable. Marking it explicitly seems to work
// around these problems.
fullscreen_handler()->MarkFullscreen(true);
background_fullscreen_hack_ = false;
} else {
// If the window becoming active has a fullscreen window on the same
// monitor then we need to reduce the size of the fullscreen window by
// 1 px. Please refer to the comments above for the reasoning behind
// this.
CheckAndHandleBackgroundFullscreenOnMonitor(
window_gaining_or_losing_activation);
}
}
void HWNDMessageHandler::RestoreEnabledIfNecessary() {
if (delegate_->IsModal() && !restored_enabled_) {
restored_enabled_ = true;
// If we were run modally, we need to undo the disabled-ness we inflicted on
// the owner's parent hierarchy.
HWND start = ::GetWindow(hwnd(), GW_OWNER);
while (start) {
::EnableWindow(start, TRUE);
start = ::GetParent(start);
}
}
}
void HWNDMessageHandler::ExecuteSystemMenuCommand(int command) {
if (command)
SendMessage(hwnd(), WM_SYSCOMMAND, static_cast<WPARAM>(command), 0);
}
void HWNDMessageHandler::TrackMouseEvents(DWORD mouse_tracking_flags) {
// Begin tracking mouse events for this HWND so that we get WM_MOUSELEAVE
// when the user moves the mouse outside this HWND's bounds.
if (active_mouse_tracking_flags_ == 0 || mouse_tracking_flags & TME_CANCEL) {
if (mouse_tracking_flags & TME_CANCEL) {
// We're about to cancel active mouse tracking, so empty out the stored
// state.
active_mouse_tracking_flags_ = 0;
} else {
active_mouse_tracking_flags_ = mouse_tracking_flags;
}
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(tme);
tme.dwFlags = mouse_tracking_flags;
tme.hwndTrack = hwnd();
tme.dwHoverTime = 0;
TrackMouseEvent(&tme);
} else if (mouse_tracking_flags != active_mouse_tracking_flags_) {
TrackMouseEvents(active_mouse_tracking_flags_ | TME_CANCEL);
TrackMouseEvents(mouse_tracking_flags);
}
}
void HWNDMessageHandler::ClientAreaSizeChanged() {
// Ignore size changes due to fullscreen windows losing activation and
// in headless mode since it maintains expected rather than actual platform
// window bounds.
if ((background_fullscreen_hack_ && !sent_window_size_changing_) ||
IsHeadless()) {
return;
}
auto ref = msg_handler_weak_factory_.GetWeakPtr();
delegate_->HandleClientSizeChanged(GetClientAreaBounds().size());
if (!ref)
return;
current_window_size_message_++;
sent_window_size_changing_ = false;
}
bool HWNDMessageHandler::GetClientAreaInsets(gfx::Insets* insets,
HMONITOR monitor) const {
if (delegate_->GetClientAreaInsets(insets, monitor))
return true;
DCHECK(insets->IsEmpty());
// Returning false causes the default handling in OnNCCalcSize() to
// be invoked.
if (!delegate_->HasNonClientView() || HasSystemFrame())
return false;
if (IsMaximized()) {
// Windows automatically adds a standard width border to all sides when a
// window is maximized.
int frame_thickness = ui::GetFrameThickness(monitor);
if (!delegate_->HasFrame())
frame_thickness -= 1;
*insets = gfx::Insets(frame_thickness);
return true;
}
*insets = gfx::Insets();
return true;
}
void HWNDMessageHandler::ResetWindowRegion(bool force, bool redraw) {
// A native frame uses the native window region, and we don't want to mess
// with it.
// WS_EX_LAYERED automatically makes clicks on transparent pixels fall
// through, but that isn't the case when using Direct3D to draw transparent
// windows. So we route translucent windows throught to the delegate to
// allow for a custom hit mask.
if (!is_translucent_ && !custom_window_region_.is_valid() &&
(IsFrameSystemDrawn() || !delegate_->HasNonClientView())) {
if (force)
SetWindowRgn(hwnd(), nullptr, redraw);
return;
}
// Changing the window region is going to force a paint. Only change the
// window region if the region really differs.
base::win::ScopedRegion current_rgn(CreateRectRgn(0, 0, 0, 0));
GetWindowRgn(hwnd(), current_rgn.get());
RECT window_rect;
GetWindowRect(hwnd(), &window_rect);
base::win::ScopedRegion new_region;
if (custom_window_region_.is_valid()) {
new_region.reset(CreateRectRgn(0, 0, 0, 0));
CombineRgn(new_region.get(), custom_window_region_.get(), nullptr,
RGN_COPY);
} else if (IsMaximized()) {
HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST);
MONITORINFO mi;
mi.cbSize = sizeof mi;
GetMonitorInfo(monitor, &mi);
RECT work_rect = mi.rcWork;
OffsetRect(&work_rect, -window_rect.left, -window_rect.top);
new_region.reset(CreateRectRgnIndirect(&work_rect));
} else {
SkPath window_mask;
delegate_->GetWindowMask(gfx::Size(window_rect.right - window_rect.left,
window_rect.bottom - window_rect.top),
&window_mask);
if (!window_mask.isEmpty())
new_region.reset(gfx::CreateHRGNFromSkPath(window_mask));
}
const bool has_current_region = current_rgn != nullptr;
const bool has_new_region = new_region != nullptr;
if (has_current_region != has_new_region ||
(has_current_region && !EqualRgn(current_rgn.get(), new_region.get()))) {
// SetWindowRgn takes ownership of the HRGN.
SetWindowRgn(hwnd(), new_region.release(), redraw);
}
}
void HWNDMessageHandler::UpdateDwmNcRenderingPolicy() {
if (IsFullscreen())
return;
DWMNCRENDERINGPOLICY policy =
custom_window_region_.is_valid() ||
delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN
? DWMNCRP_DISABLED
: DWMNCRP_ENABLED;
DwmSetWindowAttribute(hwnd(), DWMWA_NCRENDERING_POLICY, &policy,
sizeof(DWMNCRENDERINGPOLICY));
}
LRESULT HWNDMessageHandler::DefWindowProcWithRedrawLock(UINT message,
WPARAM w_param,
LPARAM l_param) {
ScopedRedrawLock lock(this);
// The Widget and HWND can be destroyed in the call to DefWindowProc, so use
// the WeakPtrFactory to avoid unlocking (and crashing) after destruction.
base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
LRESULT result = DefWindowProc(hwnd(), message, w_param, l_param);
if (!ref)
lock.CancelUnlockOperation();
return result;
}
void HWNDMessageHandler::LockUpdates() {
if (++lock_updates_count_ == 1) {
SetWindowLong(hwnd(), GWL_STYLE,
GetWindowLong(hwnd(), GWL_STYLE) & ~WS_VISIBLE);
}
}
void HWNDMessageHandler::UnlockUpdates() {
if (--lock_updates_count_ <= 0) {
SetWindowLong(hwnd(), GWL_STYLE,
GetWindowLong(hwnd(), GWL_STYLE) | WS_VISIBLE);
lock_updates_count_ = 0;
}
}
void HWNDMessageHandler::ForceRedrawWindow(int attempts) {
if (ui::IsWorkstationLocked()) {
// Presents will continue to fail as long as the input desktop is
// unavailable.
if (--attempts <= 0)
return;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&HWNDMessageHandler::ForceRedrawWindow,
msg_handler_weak_factory_.GetWeakPtr(), attempts),
base::Milliseconds(500));
return;
}
InvalidateRect(hwnd(), nullptr, FALSE);
}
bool HWNDMessageHandler::IsFrameSystemDrawn() const {
FrameMode frame_mode = delegate_->GetFrameMode();
return frame_mode == FrameMode::SYSTEM_DRAWN ||
frame_mode == FrameMode::SYSTEM_DRAWN_NO_CONTROLS;
}
bool HWNDMessageHandler::HasSystemFrame() const {
return delegate_->HasFrame() && IsFrameSystemDrawn();
}
// Message handlers ------------------------------------------------------------
void HWNDMessageHandler::OnActivateApp(BOOL active, DWORD thread_id) {
if (delegate_->HasNonClientView() && !active &&
thread_id != GetCurrentThreadId()) {
// Update the native frame if it is rendering the non-client area.
if (HasSystemFrame())
DefWindowProcWithRedrawLock(WM_NCACTIVATE, FALSE, 0);
}
}
BOOL HWNDMessageHandler::OnAppCommand(HWND window,
int command,
WORD device,
WORD keystate) {
BOOL handled = !!delegate_->HandleAppCommand(command);
SetMsgHandled(handled);
// Make sure to return TRUE if the event was handled or in some cases the
// system will execute the default handler which can cause bugs like going
// forward or back two pages instead of one.
return handled;
}
void HWNDMessageHandler::OnCancelMode() {
delegate_->HandleCancelMode();
// Need default handling, otherwise capture and other things aren't canceled.
SetMsgHandled(FALSE);
}
void HWNDMessageHandler::OnCaptureChanged(HWND window) {
delegate_->HandleCaptureLost();
}
void HWNDMessageHandler::OnClose() {
delegate_->HandleClose();
}
void HWNDMessageHandler::OnCommand(UINT notification_code,
int command,
HWND window) {
// If the notification code is > 1 it means it is control specific and we
// should ignore it.
if (notification_code > 1 || delegate_->HandleAppCommand(command))
SetMsgHandled(FALSE);
}
LRESULT HWNDMessageHandler::OnCreate(CREATESTRUCT* create_struct) {
if (is_translucent_) {
// This is part of the magic to emulate layered windows with Aura
// see the explanation elsewere when we set is_translucent_.
MARGINS margins = {-1, -1, -1, -1};
DwmExtendFrameIntoClientArea(hwnd(), &margins);
::SetProp(hwnd(), ui::kWindowTranslucent, reinterpret_cast<HANDLE>(1));
}
fullscreen_handler_->set_hwnd(hwnd());
base::win::AllowDarkModeForWindow(hwnd(), true);
// This message initializes the window so that focus border are shown for
// windows.
SendMessage(hwnd(), WM_CHANGEUISTATE, MAKELPARAM(UIS_CLEAR, UISF_HIDEFOCUS),
0);
if (!delegate_->HasFrame()) {
SetWindowLong(hwnd(), GWL_STYLE,
GetWindowLong(hwnd(), GWL_STYLE) & ~WS_CAPTION);
SendFrameChanged();
}
// Get access to a modifiable copy of the system menu.
GetSystemMenu(hwnd(), false);
if (!pointer_events_for_touch_)
RegisterTouchWindow(hwnd(), TWF_WANTPALM);
// We need to allow the delegate to size its contents since the window may not
// receive a size notification when its initial bounds are specified at window
// creation time.
ClientAreaSizeChanged();
delegate_->HandleCreate();
session_change_observer_ =
std::make_unique<ui::SessionChangeObserver>(base::BindRepeating(
&HWNDMessageHandler::OnSessionChange, base::Unretained(this)));
// If the window was initialized with a specific size/location then we know
// the DPI and thus must initialize dpi_ now. See https://crbug.com/1282804
// for details.
if (initial_bounds_valid_)
dpi_ = display::win::ScreenWin::GetDPIForHWND(hwnd());
// TODO(beng): move more of NWW::OnCreate here.
return 0;
}
void HWNDMessageHandler::OnDestroy() {
::RemoveProp(hwnd(), ui::kWindowTranslucent);
session_change_observer_.reset(nullptr);
delegate_->HandleDestroying();
// If the window going away is a fullscreen window then remove its references
// from the full screen window map.
auto& map = fullscreen_monitor_map_.Get();
const auto i = base::ranges::find(
map, this, &FullscreenWindowMonitorMap::value_type::second);
if (i != map.end())
map.erase(i);
// If we have ever returned a UIA object via WM_GETOBJECT, signal that all
// objects associated with this HWND can be discarded. See:
// https://docs.microsoft.com/en-us/windows/win32/api/uiautomationcoreapi/nf-uiautomationcoreapi-uiareturnrawelementprovider#remarks
if (did_return_uia_object_)
UiaReturnRawElementProvider(hwnd(), 0, 0, nullptr);
}
void HWNDMessageHandler::OnDisplayChange(UINT bits_per_pixel,
const gfx::Size& screen_size) {
TRACE_EVENT0("ui", "HWNDMessageHandler::OnDisplayChange");
base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
delegate_->HandleDisplayChange();
// HandleDisplayChange() may result in |this| being deleted.
if (!ref)
return;
// Force a WM_NCCALCSIZE to occur to ensure that we handle auto hide
// taskbars correctly.
SendFrameChanged();
}
LRESULT HWNDMessageHandler::OnDpiChanged(UINT msg,
WPARAM w_param,
LPARAM l_param) {
if (LOWORD(w_param) != HIWORD(w_param))
NOTIMPLEMENTED() << "Received non-square scaling factors";
TRACE_EVENT("ui", "HWNDMessageHandler::OnDpiChanged",
[&](perfetto::EventContext ctx) {
perfetto::protos::pbzero::ChromeWindowHandleEventInfo* args =
ctx.event()->set_chrome_window_handle_event_info();
args->set_dpi(LOWORD(w_param));
});
int dpi;
float scaling_factor;
if (display::Display::HasForceDeviceScaleFactor()) {
scaling_factor = display::Display::GetForcedDeviceScaleFactor();
dpi = display::win::GetDPIFromScalingFactor(scaling_factor);
} else {
dpi = LOWORD(w_param);
scaling_factor = display::win::ScreenWin::GetScaleFactorForDPI(dpi);
}
// The first WM_DPICHANGED originates from EnableChildWindowDpiMessage during
// initialization. We don't want to propagate this as the client is already
// set at the current scale factor and may cause the window to display too
// soon. See http://crbug.com/625076.
if (dpi_ == 0) {
// See https://crbug.com/1252564 for why we need to ignore the first
// OnDpiChanged message in this way.
dpi_ = dpi;
return 0;
}
dpi_ = dpi;
// Make sure the displays have up to date scale factors before updating the
// window's scale factor. Otherwise, we can be in an inconsistent state,
// in which the display a window is on has a different scale factor than the
// window, when the window handles the scale factor change.
// See https://crbug.com/1368455 for more info.
display::win::ScreenWin::UpdateDisplayInfos();
SetBoundsInternal(gfx::Rect(*reinterpret_cast<RECT*>(l_param)), false);
delegate_->HandleWindowScaleFactorChanged(scaling_factor);
return 0;
}
void HWNDMessageHandler::OnEnterMenuLoop(BOOL from_track_popup_menu) {
if (menu_depth_++ == 0)
delegate_->HandleMenuLoop(true);
}
void HWNDMessageHandler::OnEnterSizeMove() {
delegate_->HandleBeginWMSizeMove();
SetMsgHandled(FALSE);
}
LRESULT HWNDMessageHandler::OnEraseBkgnd(HDC dc) {
gfx::Insets insets;
if (delegate_->GetDwmFrameInsetsInPixels(&insets) && !insets.IsEmpty() &&
needs_dwm_frame_clear_) {
// This is necessary to avoid white flashing in the titlebar area around the
// minimize/maximize/close buttons.
needs_dwm_frame_clear_ = false;
RECT client_rect;
GetClientRect(hwnd(), &client_rect);
base::win::ScopedGDIObject<HBRUSH> brush(CreateSolidBrush(0));
// The DC and GetClientRect operate in client area coordinates.
RECT rect = {0, 0, client_rect.right, insets.top()};
FillRect(dc, &rect, brush.get());
}
// Needed to prevent resize flicker.
return 1;
}
void HWNDMessageHandler::OnExitMenuLoop(BOOL is_shortcut_menu) {
if (--menu_depth_ == 0)
delegate_->HandleMenuLoop(false);
DCHECK_GE(0, menu_depth_);
}
void HWNDMessageHandler::OnExitSizeMove() {
delegate_->HandleEndWMSizeMove();
SetMsgHandled(FALSE);
// If the window was moved to a monitor which has a fullscreen window active,
// we need to reduce the size of the fullscreen window by 1px.
CheckAndHandleBackgroundFullscreenOnMonitor(hwnd());
}
void HWNDMessageHandler::OnGetMinMaxInfo(MINMAXINFO* minmax_info) {
gfx::Size min_window_size;
gfx::Size max_window_size;
delegate_->GetMinMaxSize(&min_window_size, &max_window_size);
min_window_size = delegate_->DIPToScreenSize(min_window_size);
max_window_size = delegate_->DIPToScreenSize(max_window_size);
// Add the native frame border size to the minimum and maximum size if the
// view reports its size as the client size.
if (delegate_->WidgetSizeIsClientSize()) {
RECT client_rect, window_rect;
GetClientRect(hwnd(), &client_rect);
GetWindowRect(hwnd(), &window_rect);
CR_DEFLATE_RECT(&window_rect, &client_rect);
min_window_size.Enlarge(window_rect.right - window_rect.left,
window_rect.bottom - window_rect.top);
// Either axis may be zero, so enlarge them independently.
if (max_window_size.width())
max_window_size.Enlarge(window_rect.right - window_rect.left, 0);
if (max_window_size.height())
max_window_size.Enlarge(0, window_rect.bottom - window_rect.top);
}
minmax_info->ptMinTrackSize.x = min_window_size.width();
minmax_info->ptMinTrackSize.y = min_window_size.height();
if (max_window_size.width() || max_window_size.height()) {
if (!max_window_size.width())
max_window_size.set_width(GetSystemMetrics(SM_CXMAXTRACK));
if (!max_window_size.height())
max_window_size.set_height(GetSystemMetrics(SM_CYMAXTRACK));
minmax_info->ptMaxTrackSize.x = max_window_size.width();
minmax_info->ptMaxTrackSize.y = max_window_size.height();
}
SetMsgHandled(FALSE);
}
LRESULT HWNDMessageHandler::OnGetObject(UINT message,
WPARAM w_param,
LPARAM l_param) {
LRESULT reference_result = static_cast<LRESULT>(0L);
// Only the lower 32 bits of l_param are valid when checking the object id
// because it sometimes gets sign-extended incorrectly (but not always).
DWORD obj_id = static_cast<DWORD>(static_cast<DWORD_PTR>(l_param));
bool is_uia_request = static_cast<DWORD>(UiaRootObjectId) == obj_id;
bool is_msaa_request = static_cast<DWORD>(OBJID_CLIENT) == obj_id;
if ((is_uia_request || is_msaa_request) &&
delegate_->GetNativeViewAccessible()) {
// Expose either the UIA or the MSAA implementation, but not both, depending
// on the state of the feature flag.
if (is_uia_request &&
::switches::IsExperimentalAccessibilityPlatformUIAEnabled()) {
// Retrieve UIA object for the root view.
Microsoft::WRL::ComPtr<IRawElementProviderSimple> root;
ax_fragment_root_->GetNativeViewAccessible()->QueryInterface(
IID_PPV_ARGS(&root));
// Return the UIA object via UiaReturnRawElementProvider(). See:
// https://docs.microsoft.com/en-us/windows/win32/winauto/wm-getobject
did_return_uia_object_ = true;
reference_result =
UiaReturnRawElementProvider(hwnd(), w_param, l_param, root.Get());
} else if (is_msaa_request) {
// Retrieve MSAA dispatch object for the root view.
Microsoft::WRL::ComPtr<IAccessible> root(
delegate_->GetNativeViewAccessible());
reference_result =
LresultFromObject(IID_IAccessible, w_param, root.Get());
}
} else if (::GetFocus() == hwnd() && ax_system_caret_ &&
static_cast<DWORD>(OBJID_CARET) == obj_id) {
Microsoft::WRL::ComPtr<IAccessible> ax_system_caret_accessible =
ax_system_caret_->GetCaret();
reference_result = LresultFromObject(IID_IAccessible, w_param,
ax_system_caret_accessible.Get());
}
return reference_result;
}
LRESULT HWNDMessageHandler::OnImeMessages(UINT message,
WPARAM w_param,
LPARAM l_param) {
LRESULT result = 0;
base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
const bool msg_handled =
delegate_->HandleIMEMessage(message, w_param, l_param, &result);
if (ref.get())
SetMsgHandled(msg_handled);
return result;
}
void HWNDMessageHandler::OnInitMenu(HMENU menu) {
bool is_fullscreen = IsFullscreen();
bool is_minimized = IsMinimized();
bool is_maximized = IsMaximized();
bool is_restored = !is_fullscreen && !is_minimized && !is_maximized;
ScopedRedrawLock lock(this);
EnableMenuItemByCommand(
menu, SC_RESTORE,
delegate_->CanResize() && (is_minimized || is_maximized));
EnableMenuItemByCommand(menu, SC_MOVE, is_restored);
EnableMenuItemByCommand(menu, SC_SIZE, delegate_->CanResize() && is_restored);
EnableMenuItemByCommand(
menu, SC_MAXIMIZE,
delegate_->CanMaximize() && !is_fullscreen && !is_maximized);
EnableMenuItemByCommand(menu, SC_MINIMIZE,
delegate_->CanMinimize() && !is_minimized);
if (is_maximized && delegate_->CanResize())
::SetMenuDefaultItem(menu, SC_RESTORE, FALSE);
else if (!is_maximized && delegate_->CanMaximize())
::SetMenuDefaultItem(menu, SC_MAXIMIZE, FALSE);
}
void HWNDMessageHandler::OnInputLangChange(DWORD character_set,
HKL input_language_id) {
delegate_->HandleInputLanguageChange(character_set, input_language_id);
}
LRESULT HWNDMessageHandler::OnKeyEvent(UINT message,
WPARAM w_param,
LPARAM l_param) {
CHROME_MSG msg = {hwnd(), message, w_param, l_param,
static_cast<DWORD>(GetMessageTime())};
ui::KeyEvent key(msg);
base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
delegate_->HandleKeyEvent(&key);
if (!ref)
return 0;
if (!key.handled())
SetMsgHandled(FALSE);
return 0;
}
void HWNDMessageHandler::OnKillFocus(HWND focused_window) {
delegate_->HandleNativeBlur(focused_window);
SetMsgHandled(FALSE);
}
LRESULT HWNDMessageHandler::OnMouseActivate(UINT message,
WPARAM w_param,
LPARAM l_param) {
// Please refer to the comments in the header for the touch_down_contexts_
// member for the if statement below.
if (touch_down_contexts_)
return MA_NOACTIVATE;
// On Windows, if we select the menu item by touch and if the window at the
// location is another window on the same thread, that window gets a
// WM_MOUSEACTIVATE message and ends up activating itself, which is not
// correct. We workaround this by setting a property on the window at the
// current cursor location. We check for this property in our
// WM_MOUSEACTIVATE handler and don't activate the window if the property is
// set.
if (::GetProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow)) {
::RemoveProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow);
return MA_NOACTIVATE;
}
// TODO(beng): resolve this with the GetWindowLong() check on the subsequent
// line.
if (delegate_->HasNonClientView()) {
if (delegate_->CanActivate())
return MA_ACTIVATE;
if (delegate_->WantsMouseEventsWhenInactive())
return MA_NOACTIVATE;
return MA_NOACTIVATEANDEAT;
}
if (GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)
return MA_NOACTIVATE;
SetMsgHandled(FALSE);
return MA_ACTIVATE;
}
LRESULT HWNDMessageHandler::OnMouseRange(UINT message,
WPARAM w_param,
LPARAM l_param) {
return HandleMouseEventInternal(message, w_param, l_param, true);
}
// On some systems with a high-resolution track pad and running Windows 10,
// using the scrolling gesture (two-finger scroll) on the track pad
// causes it to also generate a WM_POINTERDOWN message if the window
// isn't focused. This leads to a WM_POINTERACTIVATE message and the window
// gaining focus and coming to the front. This code detects a
// WM_POINTERACTIVATE coming from the track pad and kills the activation
// of the window. NOTE: most other trackpad messages come in as mouse
// messages, including WM_MOUSEWHEEL instead of WM_POINTERWHEEL.
LRESULT HWNDMessageHandler::OnPointerActivate(UINT message,
WPARAM w_param,
LPARAM l_param) {
POINTER_INPUT_TYPE pointer_type;
if (::GetPointerType(GET_POINTERID_WPARAM(w_param), &pointer_type) &&
pointer_type == PT_TOUCHPAD) {
return PA_NOACTIVATE;
}
SetMsgHandled(FALSE);
return -1;
}
LRESULT HWNDMessageHandler::OnPointerEvent(UINT message,
WPARAM w_param,
LPARAM l_param) {
POINTER_INPUT_TYPE pointer_type;
// If the WM_POINTER messages are not sent from a stylus device, then we do
// not handle them to make sure we do not change the current behavior of
// touch and mouse inputs.
if (!::GetPointerType(GET_POINTERID_WPARAM(w_param), &pointer_type)) {
SetMsgHandled(FALSE);
return -1;
}
// |HandlePointerEventTypePenClient| assumes all pen events happen on the
// client area, so WM_NCPOINTER messages sent to it would eventually be
// dropped and the native frame wouldn't be able to respond to pens.
// |HandlePointerEventTypeTouchOrNonClient| handles non-client area messages
// properly. Since we don't need to distinguish between pens and fingers in
// non-client area, route the messages to that method.
if (pointer_type == PT_PEN &&
(message == WM_NCPOINTERDOWN ||
message == WM_NCPOINTERUP ||
message == WM_NCPOINTERUPDATE)) {
pointer_type = PT_TOUCH;
}
switch (pointer_type) {
case PT_PEN:
return HandlePointerEventTypePenClient(message, w_param, l_param);
case PT_TOUCH:
if (pointer_events_for_touch_) {
return HandlePointerEventTypeTouchOrNonClient(
message, w_param, l_param);
}
[[fallthrough]];
default:
break;
}
SetMsgHandled(FALSE);
return -1;
}
LRESULT HWNDMessageHandler::OnInputEvent(UINT message,
WPARAM w_param,
LPARAM l_param) {
if (!using_wm_input_)
return -1;
HRAWINPUT input_handle = reinterpret_cast<HRAWINPUT>(l_param);
// Get the size of the input record.
UINT size = 0;
UINT result = ::GetRawInputData(input_handle, RID_INPUT, nullptr, &size,
sizeof(RAWINPUTHEADER));
if (result == static_cast<UINT>(-1)) {
PLOG(ERROR) << "GetRawInputData() failed";
return 0;
}
DCHECK_EQ(0u, result);
// Retrieve the input record.
auto buffer = std::make_unique<uint8_t[]>(size);
RAWINPUT* input = reinterpret_cast<RAWINPUT*>(buffer.get());
result = ::GetRawInputData(input_handle, RID_INPUT, buffer.get(), &size,
sizeof(RAWINPUTHEADER));
if (result == static_cast<UINT>(-1)) {
PLOG(ERROR) << "GetRawInputData() failed";
return 0;
}
DCHECK_EQ(size, result);
if (input->header.dwType == RIM_TYPEMOUSE &&
input->data.mouse.usButtonFlags != RI_MOUSE_WHEEL) {
POINT cursor_pos = {0};
::GetCursorPos(&cursor_pos);
ScreenToClient(hwnd(), &cursor_pos);
ui::MouseEvent event(
ui::ET_MOUSE_MOVED, gfx::PointF(cursor_pos.x, cursor_pos.y),
gfx::PointF(cursor_pos.x, cursor_pos.y), ui::EventTimeForNow(),
GetFlagsFromRawInputMessage(input), 0);
if (!(input->data.mouse.usFlags & MOUSE_MOVE_ABSOLUTE)) {
ui::MouseEvent::DispatcherApi(&event).set_movement(
gfx::Vector2dF(input->data.mouse.lLastX, input->data.mouse.lLastY));
}
delegate_->HandleMouseEvent(&event);
}
return ::DefRawInputProc(&input, 1, sizeof(RAWINPUTHEADER));
}
void HWNDMessageHandler::OnMove(const gfx::Point& point) {
delegate_->HandleMove();
SetMsgHandled(FALSE);
}
void HWNDMessageHandler::OnMoving(UINT param, const RECT* new_bounds) {
delegate_->HandleMove();
}
LRESULT HWNDMessageHandler::OnNCActivate(UINT message,
WPARAM w_param,
LPARAM l_param) {
// Per MSDN, w_param is either TRUE or FALSE. However, MSDN also hints that:
// "If the window is minimized when this message is received, the application
// should pass the message to the DefWindowProc function."
// It is found out that the high word of w_param might be set when the window
// is minimized or restored. To handle this, w_param's high word should be
// cleared before it is converted to BOOL.
BOOL active = static_cast<BOOL>(LOWORD(w_param));
const bool paint_as_active = delegate_->ShouldPaintAsActive();
if (!delegate_->HasNonClientView()) {
SetMsgHandled(FALSE);
return 0;
}
if (!delegate_->CanActivate())
return TRUE;
if (delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN) {
// TODO(beng, et al): Hack to redraw this window and child windows
// synchronously upon activation. Not all child windows are redrawing
// themselves leading to issues like http://crbug.com/74604
// We redraw out-of-process HWNDs asynchronously to avoid hanging the
// whole app if a child HWND belonging to a hung plugin is encountered.
RedrawWindow(hwnd(), nullptr, nullptr,
RDW_NOCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW);
EnumChildWindows(hwnd(), EnumChildWindowsForRedraw, NULL);
}
// The frame may need to redraw as a result of the activation change.
// We can get WM_NCACTIVATE before we're actually visible. If we're not
// visible, no need to paint.
if (IsVisible())
delegate_->SchedulePaint();
// Calling DefWindowProc is only necessary if there's a system frame being
// drawn. Otherwise it can draw an incorrect title bar and cause visual
// corruption.
if (!delegate_->HasFrame() ||
delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN) {
SetMsgHandled(TRUE);
return TRUE;
}
return DefWindowProcWithRedrawLock(WM_NCACTIVATE, paint_as_active || active,
0);
}
LRESULT HWNDMessageHandler::OnNCCalcSize(BOOL mode, LPARAM l_param) {
// We only override the default handling if we need to specify a custom
// non-client edge width. Note that in most cases "no insets" means no
// custom width, but in fullscreen mode or when the NonClientFrameView
// requests it, we want a custom width of 0.
// Let User32 handle the first nccalcsize for captioned windows
// so it updates its internal structures (specifically caption-present)
// Without this Tile & Cascade windows won't work.
// See http://code.google.com/p/chromium/issues/detail?id=900
if (is_first_nccalc_) {
is_first_nccalc_ = false;
if (GetWindowLong(hwnd(), GWL_STYLE) & WS_CAPTION) {
SetMsgHandled(FALSE);
return 0;
}
}
RECT* client_rect =
mode ? &(reinterpret_cast<NCCALCSIZE_PARAMS*>(l_param)->rgrc[0])
: reinterpret_cast<RECT*>(l_param);
HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONULL);
if (!monitor) {
// We might end up here if the window was previously minimized and the
// user clicks on the taskbar button to restore it in the previous
// position. In that case WM_NCCALCSIZE is sent before the window
// coordinates are restored to their previous values, so our (left,top)
// would probably be (-32000,-32000) like all minimized windows. So the
// above MonitorFromWindow call fails, but if we check the window rect
// given with WM_NCCALCSIZE (which is our previous restored window
// position) we will get the correct monitor handle.
monitor = MonitorFromRect(client_rect, MONITOR_DEFAULTTONULL);
if (!monitor) {
// This is probably an extreme case that we won't hit, but if we don't
// intersect any monitor, let us not adjust the client rect since our
// window will not be visible anyway.
return 0;
}
}
gfx::Insets insets;
bool got_insets = GetClientAreaInsets(&insets, monitor);
if (!got_insets && !IsFullscreen() && !(mode && !delegate_->HasFrame())) {
SetMsgHandled(FALSE);
return 0;
}
client_rect->left += insets.left();
client_rect->top += insets.top();
client_rect->bottom -= insets.bottom();
client_rect->right -= insets.right();
if (IsMaximized()) {
// Find all auto-hide taskbars along the screen edges and adjust in by the
// thickness of the auto-hide taskbar on each such edge, so the window isn't
// treated as a "fullscreen app", which would cause the taskbars to
// disappear.
const int autohide_edges = GetAppbarAutohideEdges(monitor);
if (autohide_edges & ViewsDelegate::EDGE_LEFT)
client_rect->left += kAutoHideTaskbarThicknessPx;
if (autohide_edges & ViewsDelegate::EDGE_TOP) {
if (IsFrameSystemDrawn()) {
// Tricky bit. Due to a bug in DwmDefWindowProc()'s handling of
// WM_NCHITTEST, having any nonclient area atop the window causes the
// caption buttons to draw onscreen but not respond to mouse
// hover/clicks.
// So for a taskbar at the screen top, we can't push the
// client_rect->top down; instead, we move the bottom up by one pixel,
// which is the smallest change we can make and still get a client area
// less than the screen size. This is visibly ugly, but there seems to
// be no better solution.
--client_rect->bottom;
} else {
client_rect->top += kAutoHideTaskbarThicknessPx;
}
}
if (autohide_edges & ViewsDelegate::EDGE_RIGHT)
client_rect->right -= kAutoHideTaskbarThicknessPx;
if (autohide_edges & ViewsDelegate::EDGE_BOTTOM)
client_rect->bottom -= kAutoHideTaskbarThicknessPx;
// We cannot return WVR_REDRAW when there is nonclient area, or Windows
// exhibits bugs where client pixels and child HWNDs are mispositioned by
// the width/height of the upper-left nonclient area.
return 0;
}
// If the window bounds change, we're going to relayout and repaint anyway.
// Returning WVR_REDRAW avoids an extra paint before that of the old client
// pixels in the (now wrong) location, and thus makes actions like resizing a
// window from the left edge look slightly less broken.
// We special case when left or top insets are 0, since these conditions
// actually require another repaint to correct the layout after glass gets
// turned on and off.
if (insets.left() == 0 || insets.top() == 0)
return 0;
return mode ? WVR_REDRAW : 0;
}
LRESULT HWNDMessageHandler::OnNCCreate(LPCREATESTRUCT lpCreateStruct) {
SetMsgHandled(FALSE);
if (delegate_->HasFrame()) {
using EnableNonClientDpiScalingPtr = decltype(::EnableNonClientDpiScaling)*;
static const auto enable_non_client_dpi_scaling_func =
reinterpret_cast<EnableNonClientDpiScalingPtr>(
base::win::GetUser32FunctionPointer("EnableNonClientDpiScaling"));
called_enable_non_client_dpi_scaling_ =
!!(enable_non_client_dpi_scaling_func &&
enable_non_client_dpi_scaling_func(hwnd()));
}
return FALSE;
}
LRESULT HWNDMessageHandler::OnNCHitTest(const gfx::Point& point) {
if (!delegate_->HasNonClientView()) {
SetMsgHandled(FALSE);
return 0;
}
// Some views may overlap the non client area of the window.
// This means that we should look for these views before handing the
// hittest message off to DWM or DefWindowProc.
// If the hittest returned from the search for a view returns HTCLIENT
// then it means that we have a view overlapping the non client area.
// In all other cases we can fallback to the system default handling.
// Allow the NonClientView to handle the hittest to see if we have a view
// overlapping the non client area of the window.
POINT temp = {point.x(), point.y()};
MapWindowPoints(HWND_DESKTOP, hwnd(), &temp, 1);
int component = delegate_->GetNonClientComponent(gfx::Point(temp));
if (component == HTCLIENT)
return component;
// If the DWM is rendering the window controls, we need to give the DWM's
// default window procedure first chance to handle hit testing.
if (HasSystemFrame() &&
delegate_->GetFrameMode() != FrameMode::SYSTEM_DRAWN_NO_CONTROLS) {
LRESULT result;
if (DwmDefWindowProc(hwnd(), WM_NCHITTEST, 0,
MAKELPARAM(point.x(), point.y()), &result)) {
return result;
}
}
// If the point is specified as custom or system nonclient item, return it.
if (component != HTNOWHERE)
return component;
// Otherwise, we let Windows do all the native frame non-client handling for
// us.
LRESULT hit_test_code =
DefWindowProc(hwnd(), WM_NCHITTEST, 0, MAKELPARAM(point.x(), point.y()));
return hit_test_code;
}
void HWNDMessageHandler::OnNCPaint(HRGN rgn) {
RECT window_rect;
GetWindowRect(hwnd(), &window_rect);
RECT dirty_region;
// A value of 1 indicates paint all.
if (!rgn || rgn == reinterpret_cast<HRGN>(1)) {
dirty_region.left = 0;
dirty_region.top = 0;
dirty_region.right = window_rect.right - window_rect.left;
dirty_region.bottom = window_rect.bottom - window_rect.top;
} else {
RECT rgn_bounding_box;
GetRgnBox(rgn, &rgn_bounding_box);
if (!IntersectRect(&dirty_region, &rgn_bounding_box, &window_rect)) {
SetMsgHandled(FALSE);
return; // Dirty region doesn't intersect window bounds, bail.
}
// rgn_bounding_box is in screen coordinates. Map it to window coordinates.
OffsetRect(&dirty_region, -window_rect.left, -window_rect.top);
}
// We only do non-client painting if we're not using the system frame.
// It's required to avoid some native painting artifacts from appearing when
// the window is resized.
if (!delegate_->HasNonClientView() || IsFrameSystemDrawn()) {
// The default WM_NCPAINT handler under Aero Glass doesn't clear the
// nonclient area, so it'll remain the default white color. That area is
// invisible initially (covered by the window border) but can become
// temporarily visible on maximizing or fullscreening, so clear it here.
HDC dc = GetWindowDC(hwnd());
RECT client_rect;
::GetClientRect(hwnd(), &client_rect);
::MapWindowPoints(hwnd(), nullptr, reinterpret_cast<POINT*>(&client_rect),
2);
::OffsetRect(&client_rect, -window_rect.left, -window_rect.top);
// client_rect now is in window space.
base::win::ScopedRegion base(::CreateRectRgnIndirect(&dirty_region));
base::win::ScopedRegion client(::CreateRectRgnIndirect(&client_rect));
base::win::ScopedRegion nonclient(::CreateRectRgn(0, 0, 0, 0));
::CombineRgn(nonclient.get(), base.get(), client.get(), RGN_DIFF);
::SelectClipRgn(dc, nonclient.get());
HBRUSH brush = CreateSolidBrush(0);
::FillRect(dc, &dirty_region, brush);
::DeleteObject(brush);
::ReleaseDC(hwnd(), dc);
SetMsgHandled(FALSE);
return;
}
gfx::Size root_view_size = delegate_->GetRootViewSize();
if (gfx::Size(window_rect.right - window_rect.left,
window_rect.bottom - window_rect.top) != root_view_size) {
// If the size of the window differs from the size of the root view it
// means we're being asked to paint before we've gotten a WM_SIZE. This can
// happen when the user is interactively resizing the window. To avoid
// mass flickering we don't do anything here. Once we get the WM_SIZE we'll
// reset the region of the window which triggers another WM_NCPAINT and
// all is well.
return;
}
delegate_->HandlePaintAccelerated(gfx::Rect(dirty_region));
// When using a custom frame, we want to avoid calling DefWindowProc() since
// that may render artifacts.
SetMsgHandled(delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN);
}
LRESULT HWNDMessageHandler::OnNCUAHDrawCaption(UINT message,
WPARAM w_param,
LPARAM l_param) {
// See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
// an explanation about why we need to handle this message.
SetMsgHandled(delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN);
return 0;
}
LRESULT HWNDMessageHandler::OnNCUAHDrawFrame(UINT message,
WPARAM w_param,
LPARAM l_param) {
// See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
// an explanation about why we need to handle this message.
SetMsgHandled(delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN);
return 0;
}
void HWNDMessageHandler::OnPaint(HDC dc) {
// Call BeginPaint()/EndPaint() around the paint handling, as that seems
// to do more to actually validate the window's drawing region. This only
// appears to matter for Windows that have the WS_EX_COMPOSITED style set
// but will be valid in general too.
PAINTSTRUCT ps;
HDC display_dc = BeginPaint(hwnd(), &ps);
if (!display_dc) {
// Failing to get a DC during BeginPaint() means we won't be able to
// actually get any pixels to the screen and is very bad. This is often
// caused by handle exhaustion. Collecting some GDI statistics may aid
// tracking down the cause.
base::debug::CollectGDIUsageAndDie();
}
if (!IsRectEmpty(&ps.rcPaint)) {
HBRUSH brush = reinterpret_cast<HBRUSH>(GetStockObject(BLACK_BRUSH));
if (HasChildRenderingWindow()) {
// If there's a child window that's being rendered to then clear the
// area outside it (as WS_CLIPCHILDREN is set) with transparent black.
// Otherwise, other portions of the backing store for the window can
// flicker opaque black. http://crbug.com/586454
FillRect(ps.hdc, &ps.rcPaint, brush);
} else if (exposed_pixels_ != gfx::Size()) {
// Fill in newly exposed window client area with black to ensure Windows
// doesn't put something else there (eg. copying existing pixels). This
// isn't needed if we've just cleared the whole client area outside the
// child window above.
RECT cr;
if (GetClientRect(hwnd(), &cr)) {
// GetClientRect() always returns a rect with top/left at 0.
const gfx::Size client_area = gfx::Rect(cr).size();
// It's possible that |exposed_pixels_| height and/or width is larger
// than the client area if the window frame size changed. This isn't an
// issue since FillRect() is clipped by |ps.rcPaint|.
if (exposed_pixels_.height() > 0) {
RECT rect = {0, client_area.height() - exposed_pixels_.height(),
client_area.width(), client_area.height()};
FillRect(ps.hdc, &rect, brush);
}
if (exposed_pixels_.width() > 0) {
RECT rect = {client_area.width() - exposed_pixels_.width(), 0,
client_area.width(),
client_area.height() - exposed_pixels_.height()};
FillRect(ps.hdc, &rect, brush);
}
}
}
delegate_->HandlePaintAccelerated(gfx::Rect(ps.rcPaint));
}
exposed_pixels_ = gfx::Size();
EndPaint(hwnd(), &ps);
}
LRESULT HWNDMessageHandler::OnReflectedMessage(UINT message,
WPARAM w_param,
LPARAM l_param) {
SetMsgHandled(FALSE);
return 0;
}
LRESULT HWNDMessageHandler::OnScrollMessage(UINT message,
WPARAM w_param,
LPARAM l_param) {
CHROME_MSG msg = {hwnd(), message, w_param, l_param,
static_cast<DWORD>(GetMessageTime())};
ui::ScrollEvent event(msg);
delegate_->HandleScrollEvent(&event);
return 0;
}
LRESULT HWNDMessageHandler::OnSetCursor(UINT message,
WPARAM w_param,
LPARAM l_param) {
// Ignore system generated cursors likely caused by window management mouse
// moves while the pen is active over the window client area.
if (is_pen_active_in_client_area_)
return 1;
// current_cursor_ must be a ui::WinCursor, so that custom image cursors are
// properly ref-counted. cursor below is only used for system cursors and
// doesn't replace the current cursor so an HCURSOR can be used directly.
wchar_t* cursor = IDC_ARROW;
// Reimplement the necessary default behavior here. Calling DefWindowProc can
// trigger weird non-client painting for non-glass windows with custom frames.
// Using a ScopedRedrawLock to prevent caption rendering artifacts may allow
// content behind this window to incorrectly paint in front of this window.
// Invalidating the window to paint over either set of artifacts is not ideal.
switch (LOWORD(l_param)) {
case HTSIZE:
cursor = IDC_SIZENWSE;
break;
case HTLEFT:
case HTRIGHT:
cursor = IDC_SIZEWE;
break;
case HTTOP:
case HTBOTTOM:
cursor = IDC_SIZENS;
break;
case HTTOPLEFT:
case HTBOTTOMRIGHT:
cursor = IDC_SIZENWSE;
break;
case HTTOPRIGHT:
case HTBOTTOMLEFT:
cursor = IDC_SIZENESW;
break;
case HTCLIENT:
SetCursor(current_cursor_);
return 1;
case LOWORD(HTERROR): // Use HTERROR's LOWORD value for valid comparison.
SetMsgHandled(FALSE);
break;
default:
// Use the default value, IDC_ARROW.
break;
}
::SetCursor(LoadCursor(nullptr, cursor));
return 1;
}
void HWNDMessageHandler::OnSetFocus(HWND last_focused_window) {
delegate_->HandleNativeFocus(last_focused_window);
SetMsgHandled(FALSE);
}
LRESULT HWNDMessageHandler::OnSetIcon(UINT size_type, HICON new_icon) {
// Use a ScopedRedrawLock to avoid weird non-client painting.
return DefWindowProcWithRedrawLock(WM_SETICON, size_type,
reinterpret_cast<LPARAM>(new_icon));
}
LRESULT HWNDMessageHandler::OnSetText(const wchar_t* text) {
// Use a ScopedRedrawLock to avoid weird non-client painting.
return DefWindowProcWithRedrawLock(WM_SETTEXT, NULL,
reinterpret_cast<LPARAM>(text));
}
void HWNDMessageHandler::OnSettingChange(UINT flags, const wchar_t* section) {
if (!GetParent(hwnd()) && (flags == SPI_SETWORKAREA)) {
// Fire a dummy SetWindowPos() call, so we'll trip the code in
// OnWindowPosChanging() below that notices work area changes.
::SetWindowPos(hwnd(), nullptr, 0, 0, 0, 0,
SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOREDRAW |
SWP_NOACTIVATE | SWP_NOOWNERZORDER);
SetMsgHandled(TRUE);
} else {
if (flags == SPI_SETWORKAREA)
delegate_->HandleWorkAreaChanged();
SetMsgHandled(FALSE);
}
// If the work area is changing, then it could be as a result of the taskbar
// broadcasting the WM_SETTINGCHANGE message due to changes in auto hide
// settings, etc. Force a WM_NCCALCSIZE to occur to ensure that we handle
// this correctly.
if (flags == SPI_SETWORKAREA)
SendFrameChanged();
}
void HWNDMessageHandler::OnSize(UINT param, const gfx::Size& size) {
if (DidMinimizedChange(last_size_param_, param) && IsTopLevelWindow(hwnd()))
delegate_->HandleWindowMinimizedOrRestored(param != SIZE_MINIMIZED);
last_size_param_ = param;
RedrawWindow(hwnd(), nullptr, nullptr, RDW_INVALIDATE | RDW_ALLCHILDREN);
// ResetWindowRegion is going to trigger WM_NCPAINT. By doing it after we've
// invoked OnSize we ensure the RootView has been laid out.
ResetWindowRegion(false, true);
}
void HWNDMessageHandler::OnSizing(UINT param, RECT* rect) {
// If the aspect ratio was not specified for the window, do nothing.
if (!aspect_ratio_.has_value())
return;
// Validate the window edge param because we are seeing DCHECKs caused by
// invalid values. See https://crbug.com/1418231.
if (param < WMSZ_LEFT || param > WMSZ_BOTTOMRIGHT) {
return;
}
gfx::Rect window_rect(*rect);
SizeWindowToAspectRatio(param, &window_rect);
// TODO(apacible): Account for window borders as part of the aspect ratio.
// https://crbug/869487.
*rect = window_rect.ToRECT();
}
void HWNDMessageHandler::OnSysCommand(UINT notification_code,
const gfx::Point& point) {
// Windows uses the 4 lower order bits of |notification_code| for type-
// specific information so we must exclude this when comparing.
static const int sc_mask = 0xFFF0;
// Ignore size/move/maximize in fullscreen mode.
if (IsFullscreen() && (((notification_code & sc_mask) == SC_SIZE) ||
((notification_code & sc_mask) == SC_MOVE) ||
((notification_code & sc_mask) == SC_MAXIMIZE)))
return;
const bool window_control_action =
(notification_code & sc_mask) == SC_MINIMIZE ||
(notification_code & sc_mask) == SC_MAXIMIZE ||
(notification_code & sc_mask) == SC_RESTORE;
const bool custom_controls_frame_mode =
delegate_->GetFrameMode() == FrameMode::SYSTEM_DRAWN_NO_CONTROLS ||
delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN;
if (custom_controls_frame_mode && window_control_action)
delegate_->ResetWindowControls();
if (delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN) {
const bool window_bounds_change =
(notification_code & sc_mask) == SC_MOVE ||
(notification_code & sc_mask) == SC_SIZE;
if (window_bounds_change || window_control_action)
DestroyAXSystemCaret();
if (window_bounds_change && !IsVisible()) {
// Circumvent ScopedRedrawLocks and force visibility before entering a
// resize or move modal loop to get continuous sizing/moving feedback.
SetWindowLong(hwnd(), GWL_STYLE,
GetWindowLong(hwnd(), GWL_STYLE) | WS_VISIBLE);
}
}
// Handle SC_KEYMENU, which means that the user has pressed the ALT
// key and released it, so we should focus the menu bar.
if ((notification_code & sc_mask) == SC_KEYMENU && point.x() == 0) {
int modifiers = ui::EF_NONE;
if (ui::win::IsShiftPressed())
modifiers |= ui::EF_SHIFT_DOWN;
if (ui::win::IsCtrlPressed())
modifiers |= ui::EF_CONTROL_DOWN;
// Retrieve the status of shift and control keys to prevent consuming
// shift+alt keys, which are used by Windows to change input languages.
ui::Accelerator accelerator(ui::KeyboardCodeForWindowsKeyCode(VK_MENU),
modifiers);
delegate_->HandleAccelerator(accelerator);
return;
}
if (delegate_->HandleCommand(static_cast<int>(notification_code)))
return;
bool is_mouse_menu = (notification_code & sc_mask) == SC_MOUSEMENU;
if (is_mouse_menu)
handling_mouse_menu_ = true;
base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
// If the delegate can't handle it, the system implementation will be called.
DefWindowProc(hwnd(), WM_SYSCOMMAND, notification_code,
MAKELPARAM(point.x(), point.y()));
if (is_mouse_menu && ref)
handling_mouse_menu_ = false;
}
void HWNDMessageHandler::OnThemeChanged() {
ui::NativeThemeWin::CloseHandles();
}
void HWNDMessageHandler::OnTimeChange() {
// Call NowFromSystemTime() to force base::Time to re-initialize the clock
// from system time. Otherwise base::Time::Now() might continue to reflect the
// old system clock for some amount of time. See https://crbug.com/672906#c5
base::Time::NowFromSystemTime();
}
LRESULT HWNDMessageHandler::OnTouchEvent(UINT message,
WPARAM w_param,
LPARAM l_param) {
if (pointer_events_for_touch_) {
// Release any associated memory with this event.
CloseTouchInputHandle(reinterpret_cast<HTOUCHINPUT>(l_param));
// Claim the event is handled. This shouldn't ever happen
// because we don't register touch windows when we are using
// pointer events.
return 0;
}
// Handle touch events only on Aura for now.
WORD num_points = LOWORD(w_param);
std::unique_ptr<TOUCHINPUT[]> input(new TOUCHINPUT[num_points]);
if (ui::GetTouchInputInfoWrapper(reinterpret_cast<HTOUCHINPUT>(l_param),
num_points, input.get(),
sizeof(TOUCHINPUT))) {
// input[i].dwTime doesn't necessarily relate to the system time at all,
// so use base::TimeTicks::Now().
const base::TimeTicks event_time = base::TimeTicks::Now();
TouchEvents touch_events;
TouchIDs stale_touches(touch_ids_);
for (size_t i = 0; i < num_points; ++i) {
stale_touches.erase(input[i].dwID);
POINT point;
point.x = TOUCH_COORD_TO_PIXEL(input[i].x);
point.y = TOUCH_COORD_TO_PIXEL(input[i].y);
ScreenToClient(hwnd(), &point);
last_touch_or_pen_message_time_ = ::GetMessageTime();
gfx::Point touch_point(point.x, point.y);
auto touch_id = static_cast<ui::PointerId>(
id_generator_.GetGeneratedID(input[i].dwID));
if (input[i].dwFlags & TOUCHEVENTF_DOWN) {
touch_ids_.insert(input[i].dwID);
GenerateTouchEvent(ui::ET_TOUCH_PRESSED, touch_point, touch_id,
event_time, &touch_events);
ui::ComputeEventLatencyOSFromTOUCHINPUT(ui::ET_TOUCH_PRESSED, input[i],
event_time);
touch_down_contexts_++;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&HWNDMessageHandler::ResetTouchDownContext,
msg_handler_weak_factory_.GetWeakPtr()),
kTouchDownContextResetTimeout);
} else {
if (input[i].dwFlags & TOUCHEVENTF_MOVE) {
GenerateTouchEvent(ui::ET_TOUCH_MOVED, touch_point, touch_id,
event_time, &touch_events);
ui::ComputeEventLatencyOSFromTOUCHINPUT(ui::ET_TOUCH_MOVED, input[i],
event_time);
}
if (input[i].dwFlags & TOUCHEVENTF_UP) {
touch_ids_.erase(input[i].dwID);
GenerateTouchEvent(ui::ET_TOUCH_RELEASED, touch_point, touch_id,
event_time, &touch_events);
ui::ComputeEventLatencyOSFromTOUCHINPUT(ui::ET_TOUCH_RELEASED,
input[i], event_time);
id_generator_.ReleaseNumber(input[i].dwID);
}
}
}
// If a touch has been dropped from the list (without a TOUCH_EVENTF_UP)
// we generate a simulated TOUCHEVENTF_UP event.
for (auto touch_number : stale_touches) {
// Log that we've hit this code. When usage drops off, we can remove
// this "workaround". See https://crbug.com/811273
UMA_HISTOGRAM_BOOLEAN("TouchScreen.MissedTOUCHEVENTF_UP", true);
auto touch_id = static_cast<ui::PointerId>(
id_generator_.GetGeneratedID(touch_number));
touch_ids_.erase(touch_number);
GenerateTouchEvent(ui::ET_TOUCH_RELEASED, gfx::Point(0, 0), touch_id,
event_time, &touch_events);
id_generator_.ReleaseNumber(touch_number);
}
// Handle the touch events asynchronously. We need this because touch
// events on windows don't fire if we enter a modal loop in the context of
// a touch event.
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&HWNDMessageHandler::HandleTouchEvents,
msg_handler_weak_factory_.GetWeakPtr(), touch_events));
}
CloseTouchInputHandle(reinterpret_cast<HTOUCHINPUT>(l_param));
SetMsgHandled(FALSE);
return 0;
}
void HWNDMessageHandler::OnWindowPosChanging(WINDOWPOS* window_pos) {
TRACE_EVENT0("ui", "HWNDMessageHandler::OnWindowPosChanging");
if (ignore_window_pos_changes_) {
// If somebody's trying to toggle our visibility, change the nonclient area,
// change our Z-order, or activate us, we should probably let it go through.
if (!(window_pos->flags & ((IsVisible() ? SWP_HIDEWINDOW : SWP_SHOWWINDOW) |
SWP_FRAMECHANGED)) &&
(window_pos->flags & (SWP_NOZORDER | SWP_NOACTIVATE))) {
// Just sizing/moving the window; ignore.
window_pos->flags |= SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW;
window_pos->flags &=
static_cast<unsigned int>(~(SWP_SHOWWINDOW | SWP_HIDEWINDOW));
}
} else if (!GetParent(hwnd())) {
RECT window_rect;
const bool have_new_window_rect =
!(window_pos->flags & SWP_NOMOVE) && !(window_pos->flags & SWP_NOSIZE);
if (have_new_window_rect) {
// We should use new window rect for detecting monitor and it's
// parameters, if it is available. If we use |GetWindowRect()| instead,
// we can break our same monitor detection logic (see |same_monitor|
// below) and consequently Windows "Move to other monitor" shortcuts
// (Win+Shift+Arrows). See crbug.com/656001.
window_rect.left = window_pos->x;
window_rect.top = window_pos->y;
window_rect.right = window_pos->x + window_pos->cx;
window_rect.bottom = window_pos->y + window_pos->cy;
}
HMONITOR monitor;
gfx::Rect monitor_rect, work_area;
if ((have_new_window_rect || GetWindowRect(hwnd(), &window_rect)) &&
GetMonitorAndRects(window_rect, &monitor, &monitor_rect, &work_area)) {
bool work_area_changed = (monitor_rect == last_monitor_rect_) &&
(work_area != last_work_area_);
const bool same_monitor = monitor && (monitor == last_monitor_);
gfx::Rect expected_maximized_bounds = work_area;
if (IsMaximized()) {
// Windows automatically adds a standard width border to all sides when
// window is maximized. We should take this into account.
gfx::Insets client_area_insets;
if (GetClientAreaInsets(&client_area_insets, monitor))
// Ceil the insets after scaling to make them exclude fractional parts
// after scaling, since the result is negative.
expected_maximized_bounds.Inset(
gfx::ScaleToCeiledInsets(client_area_insets, -1));
}
// Sometimes Windows incorrectly changes bounds of maximized windows after
// attaching or detaching additional displays. In this case user can see
// non-client area of the window (that should be hidden in normal case).
// We should restore window position if problem occurs.
const bool incorrect_maximized_bounds =
IsMaximized() && have_new_window_rect &&
(expected_maximized_bounds.x() != window_pos->x ||
expected_maximized_bounds.y() != window_pos->y ||
expected_maximized_bounds.width() != window_pos->cx ||
expected_maximized_bounds.height() != window_pos->cy);
// If the size of a background fullscreen window changes again, then we
// should reset the |background_fullscreen_hack_| flag.
if (background_fullscreen_hack_ &&
(!(window_pos->flags & SWP_NOSIZE) &&
(monitor_rect.height() - window_pos->cy != 1))) {
background_fullscreen_hack_ = false;
}
const bool fullscreen_without_hack =
IsFullscreen() && !background_fullscreen_hack_;
if (same_monitor && (incorrect_maximized_bounds ||
fullscreen_without_hack || work_area_changed)) {
// A rect for the monitor we're on changed. Normally Windows notifies
// us about this (and thus we're reaching here due to the SetWindowPos()
// call in OnSettingChange() above), but with some software (e.g.
// nVidia's nView desktop manager) the work area can change asynchronous
// to any notification, and we're just sent a SetWindowPos() call with a
// new (frequently incorrect) position/size. In either case, the best
// response is to throw away the existing position/size information in
// |window_pos| and recalculate it based on the new work rect.
gfx::Rect new_window_rect;
if (IsFullscreen()) {
new_window_rect = monitor_rect;
} else if (IsMaximized()) {
new_window_rect = expected_maximized_bounds;
} else {
new_window_rect = gfx::Rect(window_rect);
new_window_rect.AdjustToFit(work_area);
}
window_pos->x = new_window_rect.x();
window_pos->y = new_window_rect.y();
window_pos->cx = new_window_rect.width();
window_pos->cy = new_window_rect.height();
// WARNING! Don't set SWP_FRAMECHANGED here, it breaks moving the child
// HWNDs for some reason.
window_pos->flags &= static_cast<unsigned int>(
~(SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW));
window_pos->flags |= SWP_NOCOPYBITS;
// Now ignore all immediately-following SetWindowPos() changes. Windows
// likes to (incorrectly) recalculate what our position/size should be
// and send us further updates.
ignore_window_pos_changes_ = true;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&HWNDMessageHandler::StopIgnoringPosChanges,
msg_handler_weak_factory_.GetWeakPtr()));
}
last_monitor_ = monitor;
last_monitor_rect_ = monitor_rect;
last_work_area_ = work_area;
}
}
RECT window_rect;
gfx::Size old_size;
if (GetWindowRect(hwnd(), &window_rect))
old_size = gfx::Rect(window_rect).size();
gfx::Size new_size = gfx::Size(window_pos->cx, window_pos->cy);
if ((old_size != new_size && !(window_pos->flags & SWP_NOSIZE)) ||
window_pos->flags & SWP_FRAMECHANGED) {
// If the window is getting larger then fill the exposed area on the next
// WM_PAINT.
exposed_pixels_ = new_size - old_size;
delegate_->HandleWindowSizeChanging();
sent_window_size_changing_ = true;
// It's possible that if Aero snap is being entered then the window size
// won't actually change. Post a message to ensure swaps will be re-enabled
// in that case.
PostMessage(hwnd(), WM_WINDOWSIZINGFINISHED, ++current_window_size_message_,
0);
// Copying the old bits can sometimes cause a flash of black when
// resizing. See https://crbug.com/739724
if (is_translucent_)
window_pos->flags |= SWP_NOCOPYBITS;
} else {
// The window size isn't changing so there are no exposed pixels.
exposed_pixels_ = gfx::Size();
}
if (ScopedFullscreenVisibility::IsHiddenForFullscreen(hwnd())) {
// Prevent the window from being made visible if we've been asked to do so.
// See comment in header as to why we might want this.
window_pos->flags &= static_cast<unsigned int>(~SWP_SHOWWINDOW);
}
if (window_pos->flags & SWP_HIDEWINDOW)
SetDwmFrameExtension(DwmFrameState::kOff);
SetMsgHandled(FALSE);
}
void HWNDMessageHandler::OnWindowPosChanged(WINDOWPOS* window_pos) {
TRACE_EVENT0("ui", "HWNDMessageHandler::OnWindowPosChanged");
base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
if (DidClientAreaSizeChange(window_pos))
ClientAreaSizeChanged();
if (!ref)
return;
if (window_pos->flags & SWP_FRAMECHANGED)
SetDwmFrameExtension(DwmFrameState::kOn);
if (window_pos->flags & SWP_SHOWWINDOW) {
delegate_->HandleVisibilityChanged(true);
SetDwmFrameExtension(DwmFrameState::kOn);
} else if (window_pos->flags & SWP_HIDEWINDOW) {
delegate_->HandleVisibilityChanged(false);
}
UpdateDwmFrame();
SetMsgHandled(FALSE);
}
LRESULT HWNDMessageHandler::OnWindowSizingFinished(UINT message,
WPARAM w_param,
LPARAM l_param) {
// Check if a newer WM_WINDOWPOSCHANGING or WM_WINDOWPOSCHANGED have been
// received after this message was posted.
if (current_window_size_message_ != w_param)
return 0;
delegate_->HandleWindowSizeUnchanged();
sent_window_size_changing_ = false;
// The window size didn't actually change, so nothing was exposed that needs
// to be filled black.
exposed_pixels_ = gfx::Size();
return 0;
}
void HWNDMessageHandler::OnSessionChange(WPARAM status_code,
const bool* is_current_session) {
// Direct3D presents are ignored while the screen is locked, so force the
// window to be redrawn on unlock.
if (status_code == WTS_SESSION_UNLOCK)
ForceRedrawWindow(10);
}
void HWNDMessageHandler::HandleTouchEvents(const TouchEvents& touch_events) {
base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
for (size_t i = 0; i < touch_events.size() && ref; ++i)
delegate_->HandleTouchEvent(const_cast<ui::TouchEvent*>(&touch_events[i]));
}
void HWNDMessageHandler::ResetTouchDownContext() {
touch_down_contexts_--;
}
LRESULT HWNDMessageHandler::HandleMouseEventInternal(UINT message,
WPARAM w_param,
LPARAM l_param,
bool track_mouse) {
// Ignore system generated mouse messages while the pen is active over the
// window client area.
if (is_pen_active_in_client_area_) {
INPUT_MESSAGE_SOURCE input_message_source;
static const auto get_current_input_message_source =
reinterpret_cast<decltype(&::GetCurrentInputMessageSource)>(
base::win::GetUser32FunctionPointer(
"GetCurrentInputMessageSource"));
if (get_current_input_message_source &&
get_current_input_message_source(&input_message_source) &&
input_message_source.deviceType == IMDT_UNAVAILABLE) {
return 0;
}
is_pen_active_in_client_area_ = false;
}
// We handle touch events in Aura. Windows generates synthesized mouse
// messages whenever there's a touch, but it doesn't give us the actual touch
// messages if it thinks the touch point is in non-client space.
if (message != WM_MOUSEWHEEL && message != WM_MOUSEHWHEEL &&
ui::IsMouseEventFromTouch(message)) {
LRESULT hittest = SendMessage(hwnd(), WM_NCHITTEST, 0, l_param);
// Always DefWindowProc on the titlebar. We could let the event fall through
// and the special handling in HandleMouseInputForCaption would take care of
// this, but in the touch case Windows does a better job.
if (hittest == HTCAPTION || hittest == HTSYSMENU)
SetMsgHandled(FALSE);
// We must let Windows handle the caption buttons if it's drawing them, or
// they won't work.
if (delegate_->GetFrameMode() == FrameMode::SYSTEM_DRAWN &&
(hittest == HTCLOSE || hittest == HTMINBUTTON ||
hittest == HTMAXBUTTON)) {
SetMsgHandled(FALSE);
}
// Let resize events fall through. Ignore everything else, as we're either
// letting Windows handle it above or we've already handled the equivalent
// touch message.
if (!IsHitTestOnResizeHandle(hittest))
return 0;
}
// Certain logitech drivers send the WM_MOUSEHWHEEL message to the parent
// followed by WM_MOUSEWHEEL messages to the child window causing a vertical
// scroll. We treat these WM_MOUSEWHEEL messages as WM_MOUSEHWHEEL
// messages.
if (message == WM_MOUSEHWHEEL)
last_mouse_hwheel_time_ = ::GetMessageTime();
if (message == WM_MOUSEWHEEL &&
::GetMessageTime() == last_mouse_hwheel_time_) {
message = WM_MOUSEHWHEEL;
}
if (message == WM_RBUTTONUP && is_right_mouse_pressed_on_caption_) {
// TODO(pkasting): Maybe handle this in DesktopWindowTreeHostWin, where we
// handle alt-space, or in the frame itself.
is_right_mouse_pressed_on_caption_ = false;
ReleaseCapture();
// |point| is in window coordinates, but WM_NCHITTEST and TrackPopupMenu()
// expect screen coordinates.
POINT screen_point = CR_POINT_INITIALIZER_FROM_LPARAM(l_param);
MapWindowPoints(hwnd(), HWND_DESKTOP, &screen_point, 1);
w_param = static_cast<WPARAM>(SendMessage(
hwnd(), WM_NCHITTEST, 0, MAKELPARAM(screen_point.x, screen_point.y)));
if (w_param == HTCAPTION || w_param == HTSYSMENU) {
ShowSystemMenuAtScreenPixelLocation(hwnd(), gfx::Point(screen_point));
return 0;
}
} else if (message == WM_NCLBUTTONDOWN &&
delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN) {
switch (w_param) {
case HTCLOSE:
case HTMINBUTTON:
case HTMAXBUTTON: {
// When the mouse is pressed down in these specific non-client areas,
// we need to tell the RootView to send the mouse pressed event (which
// sets capture, allowing subsequent WM_LBUTTONUP (note, _not_
// WM_NCLBUTTONUP) to fire so that the appropriate WM_SYSCOMMAND can be
// sent by the applicable button's callback. We _have_ to do this this
// way rather than letting Windows just send the syscommand itself (as
// would happen if we never did this dance) because for some insane
// reason DefWindowProc for WM_NCLBUTTONDOWN also renders the pressed
// window control button appearance, in the Windows classic style, over
// our view! Ick! By handling this message we prevent Windows from
// doing this undesirable thing, but that means we need to roll the
// sys-command handling ourselves.
// Combine |w_param| with common key state message flags.
w_param |= ui::win::IsCtrlPressed() ? MK_CONTROL : 0;
w_param |= ui::win::IsShiftPressed() ? MK_SHIFT : 0;
}
}
} else if (message == WM_NCRBUTTONDOWN &&
(w_param == HTCAPTION || w_param == HTSYSMENU)) {
is_right_mouse_pressed_on_caption_ = true;
// We SetCapture() to ensure we only show the menu when the button
// down and up are both on the caption. Note: this causes the button up to
// be WM_RBUTTONUP instead of WM_NCRBUTTONUP.
SetCapture();
}
LONG message_time = GetMessageTime();
CHROME_MSG msg = {hwnd(),
message,
w_param,
l_param,
static_cast<DWORD>(message_time),
{CR_GET_X_LPARAM(l_param), CR_GET_Y_LPARAM(l_param)}};
ui::MouseEvent event(msg);
if (IsSynthesizedMouseMessage(message, message_time, l_param))
event.set_flags(event.flags() | ui::EF_FROM_TOUCH);
if (event.type() == ui::ET_MOUSE_MOVED && !HasCapture() && track_mouse) {
// Windows only fires WM_MOUSELEAVE events if the application begins
// "tracking" mouse events for a given HWND during WM_MOUSEMOVE events.
// We need to call |TrackMouseEvents| to listen for WM_MOUSELEAVE.
TrackMouseEvents((message == WM_NCMOUSEMOVE) ? TME_NONCLIENT | TME_LEAVE
: TME_LEAVE);
} else if (event.type() == ui::ET_MOUSE_EXITED) {
// Reset our tracking flags so future mouse movement over this
// NativeWidget results in a new tracking session. Fall through for
// OnMouseEvent.
active_mouse_tracking_flags_ = 0;
} else if (event.type() == ui::ET_MOUSEWHEEL) {
ui::MouseWheelEvent mouse_wheel_event(msg);
// Reroute the mouse wheel to the window under the pointer if applicable.
if (ui::RerouteMouseWheel(hwnd(), w_param, l_param) ||
delegate_->HandleMouseEvent(&mouse_wheel_event)) {
SetMsgHandled(TRUE);
return 0;
} else {
return 1;
}
}
// Suppress |ET_MOUSE_MOVED| and |ET_MOUSE_DRAGGED| events from WM_MOUSE*
// messages when using WM_INPUT.
if (using_wm_input_ && (event.type() == ui::ET_MOUSE_MOVED ||
event.type() == ui::ET_MOUSE_DRAGGED)) {
return 0;
}
// There are cases where the code handling the message destroys the window,
// so use the weak ptr to check if destruction occurred or not.
base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
bool handled = false;
if (event.type() == ui::ET_MOUSE_DRAGGED) {
constexpr int kMaxDragEventsToIgnore00Move = 6;
POINT point;
point.x = event.x();
point.y = event.y();
::ClientToScreen(hwnd(), &point);
num_drag_events_after_press_++;
// Windows sometimes sends spurious WM_MOUSEMOVEs at 0,0. If this happens
// after a mouse down on a tab, it can cause a detach of the tab to 0,0.
// A past study indicated that most of the spurious moves are among the
// first 6 moves after a press, and there's a very long tail.
// If we get kMaxDragEventsToIgnore00Move mouse move events before the
// spurious 0,0 move event, the user is probably really dragging, and we
// want to allow moves to 0,0.
if (point.x == 0 && point.y == 0 &&
num_drag_events_after_press_ <= kMaxDragEventsToIgnore00Move) {
POINT cursor_pos;
::GetCursorPos(&cursor_pos);
// This constant tries to balance between detecting valid moves to 0,0
// and avoiding the detach bug happening to tabs near 0,0.
constexpr int kMinSpuriousDistance = 30;
auto distance = sqrt(pow(static_cast<float>(abs(cursor_pos.x)), 2) +
pow(static_cast<float>(abs(cursor_pos.y)), 2));
if (distance > kMinSpuriousDistance) {
SetMsgHandled(true);
return 0;
}
}
} else if (event.type() == ui::ET_MOUSE_PRESSED) {
num_drag_events_after_press_ = 0;
}
// Don't send right mouse button up to the delegate when displaying system
// command menu. This prevents left clicking in the upper left hand corner of
// an app window and then right clicking from sending the right click to the
// renderer and bringing up a web contents context menu.
if (!handling_mouse_menu_ || message != WM_RBUTTONUP)
handled = delegate_->HandleMouseEvent(&event);
if (!ref.get())
return 0;
if (!handled && message == WM_NCLBUTTONDOWN && w_param != HTSYSMENU &&
w_param != HTCAPTION &&
delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN) {
// TODO(msw): Eliminate undesired painting, or re-evaluate this workaround.
// DefWindowProc for WM_NCLBUTTONDOWN does weird non-client painting, so we
// need to call it inside a ScopedRedrawLock. This may cause other negative
// side-effects (ex/ stifling non-client mouse releases).
DefWindowProcWithRedrawLock(message, w_param, l_param);
handled = true;
}
// We need special processing for mouse input on the caption.
// Please refer to the HandleMouseInputForCaption() function for more
// information.
if (!handled)
handled = HandleMouseInputForCaption(message, w_param, l_param);
if (ref.get())
SetMsgHandled(handled);
return 0;
}
LRESULT HWNDMessageHandler::HandlePointerEventTypeTouchOrNonClient(
UINT message, WPARAM w_param, LPARAM l_param) {
UINT32 pointer_id = GET_POINTERID_WPARAM(w_param);
using GetPointerTouchInfoFn = BOOL(WINAPI*)(UINT32, POINTER_TOUCH_INFO*);
POINTER_TOUCH_INFO pointer_touch_info;
static const auto get_pointer_touch_info =
reinterpret_cast<GetPointerTouchInfoFn>(
base::win::GetUser32FunctionPointer("GetPointerTouchInfo"));
if (!get_pointer_touch_info ||
!get_pointer_touch_info(pointer_id, &pointer_touch_info)) {
SetMsgHandled(FALSE);
return -1;
}
last_touch_or_pen_message_time_ = ::GetMessageTime();
// Ignore enter/leave events, otherwise they will be converted in
// |GetTouchEventType| to ET_TOUCH_PRESSED/ET_TOUCH_RELEASED events, which
// is not correct.
if (message == WM_POINTERENTER || message == WM_POINTERLEAVE) {
SetMsgHandled(TRUE);
return 0;
}
// Increment |touch_down_contexts_| on a pointer down. This variable
// is used to debounce the WM_MOUSEACTIVATE events.
if (message == WM_POINTERDOWN || message == WM_NCPOINTERDOWN) {
touch_down_contexts_++;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&HWNDMessageHandler::ResetTouchDownContext,
msg_handler_weak_factory_.GetWeakPtr()),
kTouchDownContextResetTimeout);
}
POINTER_INFO pointer_info = pointer_touch_info.pointerInfo;
POINTER_FLAGS pointer_flags = pointer_info.pointerFlags;
// When there are touch move events but no finger is pressing on the screen,
// which most likely happens for smart board, we should ignore these events
// for now. POINTER_FLAG_INCONTACT indicates this pointer is in contact with
// the digitizer surface, which means pressing the screen.
if ((message == WM_POINTERUPDATE) &&
!(pointer_flags & POINTER_FLAG_INCONTACT)) {
SetMsgHandled(TRUE);
return 0;
}
POINT client_point = pointer_info.ptPixelLocationRaw;
ScreenToClient(hwnd(), &client_point);
gfx::Point touch_point = gfx::Point(client_point.x, client_point.y);
ui::EventType event_type = GetTouchEventType(pointer_flags);
const base::TimeTicks event_time = ui::EventTimeForNow();
auto mapped_pointer_id =
static_cast<ui::PointerId>(id_generator_.GetGeneratedID(pointer_id));
// The pressure from POINTER_TOUCH_INFO is normalized to a range between 0
// and 1024, but we define the pressure of the range of [0,1].
float pressure = static_cast<float>(pointer_touch_info.pressure) / 1024;
float radius_x =
(pointer_touch_info.rcContact.right - pointer_touch_info.rcContact.left) /
2.0;
float radius_y =
(pointer_touch_info.rcContact.bottom - pointer_touch_info.rcContact.top) /
2.0;
auto rotation_angle = static_cast<int>(pointer_touch_info.orientation);
rotation_angle %= 180;
if (rotation_angle < 0)
rotation_angle += 180;
ui::TouchEvent event(
event_type, touch_point, event_time,
ui::PointerDetails(ui::EventPointerType::kTouch, mapped_pointer_id,
radius_x, radius_y, pressure, rotation_angle),
ui::GetModifiersFromKeyState());
ui::ComputeEventLatencyOSFromPOINTER_INFO(event_type, pointer_info,
event_time);
event.latency()->AddLatencyNumberWithTimestamp(
ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT, event_time);
// Release the pointer id for touch release events.
if (event_type == ui::ET_TOUCH_RELEASED)
id_generator_.ReleaseNumber(pointer_id);
// There are cases where the code handling the message destroys the
// window, so use the weak ptr to check if destruction occurred or not.
base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
delegate_->HandleTouchEvent(&event);
if (ref) {
// Mark touch released events handled. These will usually turn into tap
// gestures, and doing this avoids propagating the event to other windows.
if (delegate_->GetFrameMode() == FrameMode::SYSTEM_DRAWN) {
// WM_NCPOINTERUP must be DefWindowProc'ed in order for the system caption
// buttons to work correctly.
if (message == WM_POINTERUP)
event.SetHandled();
} else {
// Messages on HTCAPTION should be DefWindowProc'ed, as we let Windows
// take care of dragging the window and double-tapping to maximize.
const bool on_titlebar =
SendMessage(hwnd(), WM_NCHITTEST, 0, l_param) == HTCAPTION;
// Unlike above, we must mark both WM_POINTERUP and WM_NCPOINTERUP as
// handled, in order for the custom caption buttons to work correctly.
if (event_type == ui::ET_TOUCH_RELEASED && !on_titlebar)
event.SetHandled();
}
SetMsgHandled(event.handled());
}
return 0;
}
LRESULT HWNDMessageHandler::HandlePointerEventTypePen(
UINT message,
UINT32 pointer_id,
POINTER_PEN_INFO pointer_pen_info) {
POINT client_point = pointer_pen_info.pointerInfo.ptPixelLocationRaw;
ScreenToClient(hwnd(), &client_point);
gfx::Point point = gfx::Point(client_point.x, client_point.y);
std::unique_ptr<ui::Event> event = pen_processor_.GenerateEvent(
message, pointer_id, pointer_pen_info, point);
// There are cases where the code handling the message destroys the
// window, so use the weak ptr to check if destruction occurred or not.
base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
if (event) {
if (event->IsTouchEvent()) {
delegate_->HandleTouchEvent(event->AsTouchEvent());
} else {
CHECK(event->IsMouseEvent());
delegate_->HandleMouseEvent(event->AsMouseEvent());
}
last_touch_or_pen_message_time_ = ::GetMessageTime();
is_pen_active_in_client_area_ = true;
}
// Always mark as handled as we don't want to generate WM_MOUSE compatiblity
// events.
if (ref)
SetMsgHandled(TRUE);
return 0;
}
LRESULT HWNDMessageHandler::HandlePointerEventTypePenClient(UINT message,
WPARAM w_param,
LPARAM l_param) {
UINT32 pointer_id = GET_POINTERID_WPARAM(w_param);
POINTER_PEN_INFO pointer_pen_info;
if (!GetPointerPenInfo(pointer_id, &pointer_pen_info)) {
SetMsgHandled(FALSE);
return -1;
}
return HandlePointerEventTypePen(message, pointer_id, pointer_pen_info);
}
bool HWNDMessageHandler::IsSynthesizedMouseMessage(unsigned int message,
int message_time,
LPARAM l_param) {
if (ui::IsMouseEventFromTouch(message))
return true;
// Ignore mouse messages which occur at the same location as the current
// cursor position and within a time difference of 500 ms from the last
// touch message.
if (last_touch_or_pen_message_time_ &&
message_time >= last_touch_or_pen_message_time_ &&
((message_time - last_touch_or_pen_message_time_) <=
kSynthesizedMouseMessagesTimeDifference)) {
POINT mouse_location = CR_POINT_INITIALIZER_FROM_LPARAM(l_param);
::ClientToScreen(hwnd(), &mouse_location);
POINT cursor_pos = {0};
::GetCursorPos(&cursor_pos);
return memcmp(&cursor_pos, &mouse_location, sizeof(POINT)) == 0;
}
return false;
}
void HWNDMessageHandler::PerformDwmTransition() {
dwm_transition_desired_ = false;
UpdateDwmNcRenderingPolicy();
// Don't redraw the window here, because we need to hide and show the window
// which will also trigger a redraw.
ResetWindowRegion(true, false);
// The non-client view needs to update too.
delegate_->HandleFrameChanged();
// This calls DwmExtendFrameIntoClientArea which must be called when DWM
// composition state changes.
UpdateDwmFrame();
if (IsVisible() && IsFrameSystemDrawn()) {
// For some reason, we need to hide the window after we change from a custom
// frame to a native frame. If we don't, the client area will be filled
// with black. This seems to be related to an interaction between DWM and
// SetWindowRgn, but the details aren't clear. Additionally, we need to
// specify SWP_NOZORDER here, otherwise if you have multiple chrome windows
// open they will re-appear with a non-deterministic Z-order.
// Note: caused http://crbug.com/895855, where a laptop lid close+reopen
// puts window in the background but acts like a foreground window. Fixed by
// not calling this unless DWM composition actually changes. Finally, since
// we don't want windows stealing focus if they're not already active, we
// set SWP_NOACTIVATE.
UINT flags = SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE;
SetWindowPos(hwnd(), nullptr, 0, 0, 0, 0, flags | SWP_HIDEWINDOW);
SetWindowPos(hwnd(), nullptr, 0, 0, 0, 0, flags | SWP_SHOWWINDOW);
}
}
void HWNDMessageHandler::UpdateDwmFrame() {
TRACE_EVENT0("ui", "HWNDMessageHandler::UpdateDwmFrame");
gfx::Insets insets;
if (delegate_->GetDwmFrameInsetsInPixels(&insets)) {
MARGINS margins = {insets.left(), insets.right(), insets.top(),
insets.bottom()};
DwmExtendFrameIntoClientArea(hwnd(), &margins);
}
}
void HWNDMessageHandler::GenerateTouchEvent(ui::EventType event_type,
const gfx::Point& point,
ui::PointerId id,
base::TimeTicks time_stamp,
TouchEvents* touch_events) {
ui::TouchEvent event(event_type, point, time_stamp,
ui::PointerDetails(ui::EventPointerType::kTouch, id));
event.set_flags(ui::GetModifiersFromKeyState());
event.latency()->AddLatencyNumberWithTimestamp(
ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT, time_stamp);
touch_events->push_back(event);
}
bool HWNDMessageHandler::HandleMouseInputForCaption(unsigned int message,
WPARAM w_param,
LPARAM l_param) {
// If we are receive a WM_NCLBUTTONDOWN messsage for the caption, the
// following things happen.
// 1. This message is defproced which will post a WM_SYSCOMMAND message with
// SC_MOVE and a constant 0x0002 which is documented on msdn as
// SC_DRAGMOVE.
// 2. The WM_SYSCOMMAND message is defproced in our handler which works
// correctly in all cases except the case when we click on the caption
// and hold. The defproc appears to try and detect whether a mouse move
// is going to happen presumably via the DragEnter or a similar
// implementation which in its modal loop appears to only peek for
// mouse input briefly.
// 3. Our workhorse message pump relies on the tickler posted message to get
// control during modal loops which does not happen in the above case for
// a while leading to the problem where activity on the page pauses
// briefly or at times stops for a while.
// To fix this we don't defproc the WM_NCLBUTTONDOWN message and instead wait
// for the subsequent WM_NCMOUSEMOVE/WM_MOUSEMOVE message. Once we receive
// these messages and the mouse actually moved, we defproc the
// WM_NCLBUTTONDOWN message.
bool handled = false;
switch (message) {
case WM_NCLBUTTONDOWN: {
if (w_param == HTCAPTION) {
left_button_down_on_caption_ = true;
// Cache the location where the click occurred. We use this in the
// WM_NCMOUSEMOVE message to determine if the mouse actually moved.F
caption_left_button_click_pos_.set_x(CR_GET_X_LPARAM(l_param));
caption_left_button_click_pos_.set_y(CR_GET_Y_LPARAM(l_param));
handled = true;
}
break;
}
// WM_NCMOUSEMOVE is received for normal drags which originate on the
// caption and stay there.
// WM_MOUSEMOVE can be received for drags which originate on the caption
// and move towards the client area.
case WM_MOUSEMOVE:
case WM_NCMOUSEMOVE: {
if (!left_button_down_on_caption_)
break;
bool should_handle_pending_ncl_button_down = true;
// Check if the mouse actually moved.
if (message == WM_NCMOUSEMOVE) {
if (caption_left_button_click_pos_.x() == CR_GET_X_LPARAM(l_param) &&
caption_left_button_click_pos_.y() == CR_GET_Y_LPARAM(l_param)) {
should_handle_pending_ncl_button_down = false;
}
}
if (should_handle_pending_ncl_button_down) {
l_param = MAKELPARAM(caption_left_button_click_pos_.x(),
caption_left_button_click_pos_.y());
// TODO(msw): Eliminate undesired painting, or re-evaluate this
// workaround.
// DefWindowProc for WM_NCLBUTTONDOWN does weird non-client painting,
// so we need to call it inside a ScopedRedrawLock. This may cause
// other negative side-effects
// (ex/ stifling non-client mouse releases).
// We may be deleted in the context of DefWindowProc. Don't refer to
// any member variables after the DefWindowProc call.
left_button_down_on_caption_ = false;
if (delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN) {
DefWindowProcWithRedrawLock(WM_NCLBUTTONDOWN, HTCAPTION, l_param);
} else {
DefWindowProc(hwnd(), WM_NCLBUTTONDOWN, HTCAPTION, l_param);
}
}
break;
}
case WM_NCMOUSELEAVE: {
// If the DWM is rendering the window controls, we need to give the DWM's
// default window procedure the chance to repaint the window border icons
if (HasSystemFrame())
handled = DwmDefWindowProc(hwnd(), WM_NCMOUSELEAVE, 0, 0, nullptr) != 0;
break;
}
default:
left_button_down_on_caption_ = false;
break;
}
return handled;
}
void HWNDMessageHandler::SetBoundsInternal(const gfx::Rect& bounds_in_pixels,
bool force_size_changed) {
gfx::Size old_size = GetClientAreaBounds().size();
// In headless update the expected window bounds and notify the delegate
// pretending the platform window size has been changed.
if (IsHeadless()) {
SetHeadlessWindowBounds(bounds_in_pixels);
if (old_size != bounds_in_pixels.size() || force_size_changed) {
delegate_->HandleClientSizeChanged(GetClientAreaBounds().size());
}
return;
}
SetWindowPos(hwnd(), nullptr, bounds_in_pixels.x(), bounds_in_pixels.y(),
bounds_in_pixels.width(), bounds_in_pixels.height(),
SWP_NOACTIVATE | SWP_NOZORDER);
// If HWND size is not changed, we will not receive standard size change
// notifications. If |force_size_changed| is |true|, we should pretend size is
// changed.
if (old_size == bounds_in_pixels.size() && force_size_changed &&
!background_fullscreen_hack_) {
delegate_->HandleClientSizeChanged(GetClientAreaBounds().size());
ResetWindowRegion(false, true);
}
}
void HWNDMessageHandler::CheckAndHandleBackgroundFullscreenOnMonitor(
HWND window) {
HMONITOR monitor = MonitorFromWindow(window, MONITOR_DEFAULTTOPRIMARY);
FullscreenWindowMonitorMap::iterator iter =
fullscreen_monitor_map_.Get().find(monitor);
if (iter != fullscreen_monitor_map_.Get().end()) {
DCHECK(iter->second);
if (window != iter->second->hwnd())
iter->second->OnBackgroundFullscreen();
}
}
void HWNDMessageHandler::OnBackgroundFullscreen() {
DCHECK(IsFullscreen());
// Reduce the bounds of the window by 1px to ensure that Windows does
// not treat this like a fullscreen window.
MONITORINFO monitor_info = {sizeof(monitor_info)};
GetMonitorInfo(MonitorFromWindow(hwnd(), MONITOR_DEFAULTTOPRIMARY),
&monitor_info);
gfx::Rect shrunk_rect(monitor_info.rcMonitor);
shrunk_rect.set_height(shrunk_rect.height() - 1);
background_fullscreen_hack_ = true;
SetBoundsInternal(shrunk_rect, false);
// Inform the taskbar that this window is no longer a fullscreen window so it
// can bring itself to the top of the Z-Order. The taskbar heuristics to
// detect fullscreen windows are not reliable. Marking it explicitly seems to
// work around these problems.
fullscreen_handler()->MarkFullscreen(false);
}
void HWNDMessageHandler::DestroyAXSystemCaret() {
ax_system_caret_ = nullptr;
}
void HWNDMessageHandler::SizeWindowToAspectRatio(UINT param,
gfx::Rect* window_rect) {
gfx::Size min_window_size;
gfx::Size max_window_size;
delegate_->GetMinMaxSize(&min_window_size, &max_window_size);
min_window_size = delegate_->DIPToScreenSize(min_window_size);
max_window_size = delegate_->DIPToScreenSize(max_window_size);
absl::optional<gfx::Size> max_size_param;
if (!max_window_size.IsEmpty())
max_size_param = max_window_size;
gfx::SizeRectToAspectRatioWithExcludedMargin(
GetWindowResizeEdge(param), aspect_ratio_.value(), min_window_size,
max_size_param, excluded_margin_, *window_rect);
}
POINT HWNDMessageHandler::GetCursorPos() const {
if (mock_cursor_position_.has_value())
return mock_cursor_position_.value().ToPOINT();
POINT cursor_pos = {};
::GetCursorPos(&cursor_pos);
return cursor_pos;
}
void HWNDMessageHandler::SetHeadlessWindowBounds(const gfx::Rect& bounds) {
DCHECK(IsHeadless());
if (headless_mode_window_->bounds != bounds) {
headless_mode_window_->bounds = bounds;
delegate_->HandleHeadlessWindowBoundsChanged(bounds);
}
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/win/hwnd_message_handler.cc | C++ | unknown | 151,449 |
// 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_WIN_HWND_MESSAGE_HANDLER_H_
#define UI_VIEWS_WIN_HWND_MESSAGE_HANDLER_H_
#include <windows.h>
#include <stddef.h>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "base/lazy_instance.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "base/scoped_observation.h"
#include "base/win/scoped_gdi_object.h"
#include "base/win/win_util.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/accessibility/platform/ax_fragment_root_delegate_win.h"
#include "ui/base/ime/input_method.h"
#include "ui/base/ime/input_method_observer.h"
#include "ui/base/ui_base_types.h"
#include "ui/base/win/window_event_target.h"
#include "ui/events/event.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/sequential_id_generator.h"
#include "ui/gfx/win/msg_util.h"
#include "ui/gfx/win/window_impl.h"
#include "ui/views/views_export.h"
#include "ui/views/win/pen_event_processor.h"
#include "ui/views/win/scoped_enable_unadjusted_mouse_events_win.h"
namespace gfx {
class ImageSkia;
class Insets;
} // namespace gfx
namespace ui {
class AXFragmentRootWin;
class AXSystemCaretWin;
class SessionChangeObserver;
class TextInputClient;
class ViewProp;
class WinCursor;
} // namespace ui
namespace views {
class FullscreenHandler;
class HWNDMessageHandlerDelegate;
namespace test {
class DesktopWindowTreeHostWinTestApi;
}
// These two messages aren't defined in winuser.h, but they are sent to windows
// with captions. They appear to paint the window caption and frame.
// Unfortunately if you override the standard non-client rendering as we do
// with CustomFrameWindow, sometimes Windows (not deterministically
// reproducibly but definitely frequently) will send these messages to the
// window and paint the standard caption/title over the top of the custom one.
// So we need to handle these messages in CustomFrameWindow to prevent this
// from happening.
constexpr int WM_NCUAHDRAWCAPTION = 0xAE;
constexpr int WM_NCUAHDRAWFRAME = 0xAF;
// The HWNDMessageHandler sends this message to itself on
// WM_WINDOWPOSCHANGING. It's used to inform the client if a
// WM_WINDOWPOSCHANGED won't be received.
constexpr int WM_WINDOWSIZINGFINISHED = WM_USER;
// An object that handles messages for a HWND that implements the views
// "Custom Frame" look. The purpose of this class is to isolate the windows-
// specific message handling from the code that wraps it. It is intended to be
// used by both a views::NativeWidget and an aura::WindowTreeHost
// implementation.
// TODO(beng): This object should eventually *become* the WindowImpl.
class VIEWS_EXPORT HWNDMessageHandler : public gfx::WindowImpl,
public ui::InputMethodObserver,
public ui::WindowEventTarget,
public ui::AXFragmentRootDelegateWin {
public:
// See WindowImpl for details on |debugging_id|.
HWNDMessageHandler(HWNDMessageHandlerDelegate* delegate,
const std::string& debugging_id);
HWNDMessageHandler(const HWNDMessageHandler&) = delete;
HWNDMessageHandler& operator=(const HWNDMessageHandler&) = delete;
~HWNDMessageHandler() override;
void Init(HWND parent, const gfx::Rect& bounds, bool headless_mode);
void InitModalType(ui::ModalType modal_type);
void Close();
void CloseNow();
gfx::Rect GetWindowBoundsInScreen() const;
gfx::Rect GetClientAreaBoundsInScreen() const;
gfx::Rect GetRestoredBounds() const;
// This accounts for the case where the widget size is the client size.
gfx::Rect GetClientAreaBounds() const;
void GetWindowPlacement(gfx::Rect* bounds,
ui::WindowShowState* show_state) const;
// Sets the bounds of the HWND to |bounds_in_pixels|. If the HWND size is not
// changed, |force_size_changed| determines if we should pretend it is.
void SetBounds(const gfx::Rect& bounds_in_pixels, bool force_size_changed);
void SetSize(const gfx::Size& size);
void CenterWindow(const gfx::Size& size);
void SetRegion(HRGN rgn);
void StackAbove(HWND other_hwnd);
void StackAtTop();
// Shows the window. If |show_state| is maximized, |pixel_restore_bounds| is
// the bounds to restore the window to when going back to normal.
void Show(ui::WindowShowState show_state,
const gfx::Rect& pixel_restore_bounds);
void Hide();
void Maximize();
void Minimize();
void Restore();
void Activate();
void Deactivate();
void SetAlwaysOnTop(bool on_top);
bool IsVisible() const;
bool IsActive() const;
bool IsMinimized() const;
bool IsMaximized() const;
bool IsFullscreen() const;
bool IsAlwaysOnTop() const;
bool IsHeadless() const;
bool RunMoveLoop(const gfx::Vector2d& drag_offset, bool hide_on_escape);
void EndMoveLoop();
// Tells the HWND its client area has changed.
void SendFrameChanged();
void FlashFrame(bool flash);
void ClearNativeFocus();
void SetCapture();
void ReleaseCapture();
bool HasCapture() const;
FullscreenHandler* fullscreen_handler() { return fullscreen_handler_.get(); }
void SetVisibilityChangedAnimationsEnabled(bool enabled);
// Returns true if the title changed.
bool SetTitle(const std::u16string& title);
void SetCursor(scoped_refptr<ui::WinCursor> cursor);
void FrameTypeChanged();
void PaintAsActiveChanged();
void SetWindowIcons(const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon);
void set_use_system_default_icon(bool use_system_default_icon) {
use_system_default_icon_ = use_system_default_icon;
}
// 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.
void SetFullscreen(bool fullscreen, int64_t target_display_id);
// Updates the aspect ratio of the window.
void SetAspectRatio(float aspect_ratio, const gfx::Size& excluded_mar);
// Updates the window style to reflect whether it can be resized or maximized.
void SizeConstraintsChanged();
// Returns true if content is rendered to a child window instead of directly
// to this window.
bool HasChildRenderingWindow();
void set_is_translucent(bool is_translucent) {
is_translucent_ = is_translucent;
}
bool is_translucent() const { return is_translucent_; }
std::unique_ptr<aura::ScopedEnableUnadjustedMouseEvents>
RegisterUnadjustedMouseEvent();
void set_using_wm_input(bool using_wm_input) {
using_wm_input_ = using_wm_input;
}
bool using_wm_input() { return using_wm_input_; }
private:
friend class ::views::test::DesktopWindowTreeHostWinTestApi;
using TouchIDs = std::set<DWORD>;
enum class DwmFrameState { kOff, kOn };
// Overridden from WindowImpl:
HICON GetDefaultWindowIcon() const override;
HICON GetSmallWindowIcon() const override;
LRESULT OnWndProc(UINT message, WPARAM w_param, LPARAM l_param) override;
// Overridden from InputMethodObserver
void OnFocus() override;
void OnBlur() override;
void OnCaretBoundsChanged(const ui::TextInputClient* client) override;
void OnTextInputStateChanged(const ui::TextInputClient* client) override;
void OnInputMethodDestroyed(const ui::InputMethod* input_method) override;
// Overridden from WindowEventTarget
LRESULT HandleMouseMessage(unsigned int message,
WPARAM w_param,
LPARAM l_param,
bool* handled) override;
LRESULT HandleKeyboardMessage(unsigned int message,
WPARAM w_param,
LPARAM l_param,
bool* handled) override;
LRESULT HandleTouchMessage(unsigned int message,
WPARAM w_param,
LPARAM l_param,
bool* handled) override;
LRESULT HandlePointerMessage(unsigned int message,
WPARAM w_param,
LPARAM l_param,
bool* handled) override;
LRESULT HandleInputMessage(unsigned int message,
WPARAM w_param,
LPARAM l_param,
bool* handled) override;
LRESULT HandleScrollMessage(unsigned int message,
WPARAM w_param,
LPARAM l_param,
bool* handled) override;
LRESULT HandleNcHitTestMessage(unsigned int message,
WPARAM w_param,
LPARAM l_param,
bool* handled) override;
void HandleParentChanged() override;
void ApplyPinchZoomScale(float scale) override;
void ApplyPinchZoomBegin() override;
void ApplyPinchZoomEnd() override;
void ApplyPanGestureScroll(int scroll_x, int scroll_y) override;
void ApplyPanGestureFling(int scroll_x, int scroll_y) override;
void ApplyPanGestureScrollBegin(int scroll_x, int scroll_y) override;
void ApplyPanGestureScrollEnd(bool transitioning_to_pinch) override;
void ApplyPanGestureFlingBegin() override;
void ApplyPanGestureFlingEnd() override;
// Overridden from AXFragmentRootDelegateWin.
gfx::NativeViewAccessible GetChildOfAXFragmentRoot() override;
gfx::NativeViewAccessible GetParentOfAXFragmentRoot() override;
bool IsAXFragmentRootAControlElement() override;
void ApplyPanGestureEvent(int scroll_x,
int scroll_y,
ui::EventMomentumPhase momentum_phase,
ui::ScrollEventPhase phase);
// Returns the auto-hide edges of the appbar. See
// ViewsDelegate::GetAppbarAutohideEdges() for details. If the edges change,
// OnAppbarAutohideEdgesChanged() is called.
int GetAppbarAutohideEdges(HMONITOR monitor);
// Callback if the autohide edges have changed. See
// ViewsDelegate::GetAppbarAutohideEdges() for details.
void OnAppbarAutohideEdgesChanged();
// Can be called after the delegate has had the opportunity to set focus and
// did not do so.
void SetInitialFocus();
// Called after the WM_ACTIVATE message has been processed by the default
// windows procedure.
void PostProcessActivateMessage(int activation_state,
bool minimized,
HWND window_gaining_or_losing_activation);
// Enables disabled owner windows that may have been disabled due to this
// window's modality.
void RestoreEnabledIfNecessary();
// Executes the specified SC_command.
void ExecuteSystemMenuCommand(int command);
// Start tracking all mouse events so that this window gets sent mouse leave
// messages too.
void TrackMouseEvents(DWORD mouse_tracking_flags);
// Responds to the client area changing size, either at window creation time
// or subsequently.
void ClientAreaSizeChanged();
// Returns true if |insets| was modified to define a custom client area for
// the window, false if the default client area should be used. If false is
// returned, |insets| is not modified. |monitor| is the monitor this
// window is on. Normally that would be determined from the HWND, but
// during WM_NCCALCSIZE Windows does not return the correct monitor for the
// HWND, so it must be passed in explicitly (see HWNDMessageHandler::
// OnNCCalcSize for more details).
bool GetClientAreaInsets(gfx::Insets* insets, HMONITOR monitor) const;
// Resets the window region for the current widget bounds if necessary.
// If |force| is true, the window region is reset to NULL even for native
// frame windows.
void ResetWindowRegion(bool force, bool redraw);
// Enables or disables rendering of the non-client (glass) area by DWM,
// under Vista and above, depending on whether the caller has requested a
// custom frame.
void UpdateDwmNcRenderingPolicy();
// Calls DefWindowProc, safely wrapping the call in a ScopedRedrawLock to
// prevent frame flicker. DefWindowProc handling can otherwise render the
// classic-look window title bar directly.
LRESULT DefWindowProcWithRedrawLock(UINT message,
WPARAM w_param,
LPARAM l_param);
// Lock or unlock the window from being able to redraw itself in response to
// updates to its invalid region.
class ScopedRedrawLock;
void LockUpdates();
void UnlockUpdates();
// Stops ignoring SetWindowPos() requests (see below).
void StopIgnoringPosChanges() { ignore_window_pos_changes_ = false; }
// Attempts to force the window to be redrawn, ensuring that it gets
// onscreen.
void ForceRedrawWindow(int attempts);
// Returns whether Windows should help with frame rendering (i.e. we're using
// the glass frame).
bool IsFrameSystemDrawn() const;
// Returns true if IsFrameSystemDrawn() and there's actually a frame to draw.
bool HasSystemFrame() const;
// Adds or removes the frame extension into client area with
// DwmExtendFrameIntoClientArea.
void SetDwmFrameExtension(DwmFrameState state);
// Message Handlers ----------------------------------------------------------
CR_BEGIN_MSG_MAP_EX(HWNDMessageHandler)
// Range handlers must go first!
CR_MESSAGE_RANGE_HANDLER_EX(WM_MOUSEFIRST, WM_MOUSELAST, OnMouseRange)
CR_MESSAGE_RANGE_HANDLER_EX(WM_NCMOUSEMOVE, WM_NCXBUTTONDBLCLK,
OnMouseRange)
// CustomFrameWindow hacks
CR_MESSAGE_HANDLER_EX(WM_NCUAHDRAWCAPTION, OnNCUAHDrawCaption)
CR_MESSAGE_HANDLER_EX(WM_NCUAHDRAWFRAME, OnNCUAHDrawFrame)
// Win 8.1 and newer
CR_MESSAGE_HANDLER_EX(WM_DPICHANGED, OnDpiChanged)
// Non-atlcrack.h handlers
CR_MESSAGE_HANDLER_EX(WM_GETOBJECT, OnGetObject)
// Mouse events.
CR_MESSAGE_HANDLER_EX(WM_MOUSEACTIVATE, OnMouseActivate)
CR_MESSAGE_HANDLER_EX(WM_MOUSELEAVE, OnMouseRange)
CR_MESSAGE_HANDLER_EX(WM_NCMOUSELEAVE, OnMouseRange)
CR_MESSAGE_HANDLER_EX(WM_SETCURSOR, OnSetCursor);
// Pointer events.
CR_MESSAGE_HANDLER_EX(WM_POINTERACTIVATE, OnPointerActivate)
CR_MESSAGE_HANDLER_EX(WM_POINTERDOWN, OnPointerEvent)
CR_MESSAGE_HANDLER_EX(WM_POINTERUP, OnPointerEvent)
CR_MESSAGE_HANDLER_EX(WM_POINTERUPDATE, OnPointerEvent)
CR_MESSAGE_HANDLER_EX(WM_POINTERENTER, OnPointerEvent)
CR_MESSAGE_HANDLER_EX(WM_POINTERLEAVE, OnPointerEvent)
CR_MESSAGE_HANDLER_EX(WM_NCPOINTERDOWN, OnPointerEvent)
CR_MESSAGE_HANDLER_EX(WM_NCPOINTERUP, OnPointerEvent)
CR_MESSAGE_HANDLER_EX(WM_NCPOINTERUPDATE, OnPointerEvent)
// Key events.
CR_MESSAGE_HANDLER_EX(WM_KEYDOWN, OnKeyEvent)
CR_MESSAGE_HANDLER_EX(WM_KEYUP, OnKeyEvent)
CR_MESSAGE_HANDLER_EX(WM_SYSKEYDOWN, OnKeyEvent)
CR_MESSAGE_HANDLER_EX(WM_SYSKEYUP, OnKeyEvent)
CR_MESSAGE_HANDLER_EX(WM_INPUT, OnInputEvent)
// IME Events.
CR_MESSAGE_HANDLER_EX(WM_IME_SETCONTEXT, OnImeMessages)
CR_MESSAGE_HANDLER_EX(WM_IME_STARTCOMPOSITION, OnImeMessages)
CR_MESSAGE_HANDLER_EX(WM_IME_COMPOSITION, OnImeMessages)
CR_MESSAGE_HANDLER_EX(WM_IME_ENDCOMPOSITION, OnImeMessages)
CR_MESSAGE_HANDLER_EX(WM_IME_REQUEST, OnImeMessages)
CR_MESSAGE_HANDLER_EX(WM_IME_NOTIFY, OnImeMessages)
CR_MESSAGE_HANDLER_EX(WM_CHAR, OnImeMessages)
CR_MESSAGE_HANDLER_EX(WM_SYSCHAR, OnImeMessages)
// Scroll events
CR_MESSAGE_HANDLER_EX(WM_VSCROLL, OnScrollMessage)
CR_MESSAGE_HANDLER_EX(WM_HSCROLL, OnScrollMessage)
// Touch Events.
CR_MESSAGE_HANDLER_EX(WM_TOUCH, OnTouchEvent)
CR_MESSAGE_HANDLER_EX(WM_WINDOWSIZINGFINISHED, OnWindowSizingFinished)
// Uses the general handler macro since the specific handler macro
// MSG_WM_NCACTIVATE would convert WPARAM type to BOOL type. The high
// word of WPARAM could be set when the window is minimized or restored.
CR_MESSAGE_HANDLER_EX(WM_NCACTIVATE, OnNCActivate)
// This list is in _ALPHABETICAL_ order! OR I WILL HURT YOU.
CR_MSG_WM_ACTIVATEAPP(OnActivateApp)
CR_MSG_WM_APPCOMMAND(OnAppCommand)
CR_MSG_WM_CANCELMODE(OnCancelMode)
CR_MSG_WM_CAPTURECHANGED(OnCaptureChanged)
CR_MSG_WM_CLOSE(OnClose)
CR_MSG_WM_COMMAND(OnCommand)
CR_MSG_WM_CREATE(OnCreate)
CR_MSG_WM_DESTROY(OnDestroy)
CR_MSG_WM_DISPLAYCHANGE(OnDisplayChange)
CR_MSG_WM_ENTERMENULOOP(OnEnterMenuLoop)
CR_MSG_WM_EXITMENULOOP(OnExitMenuLoop)
CR_MSG_WM_ENTERSIZEMOVE(OnEnterSizeMove)
CR_MSG_WM_ERASEBKGND(OnEraseBkgnd)
CR_MSG_WM_EXITSIZEMOVE(OnExitSizeMove)
CR_MSG_WM_GETMINMAXINFO(OnGetMinMaxInfo)
CR_MSG_WM_INITMENU(OnInitMenu)
CR_MSG_WM_INPUTLANGCHANGE(OnInputLangChange)
CR_MSG_WM_KILLFOCUS(OnKillFocus)
CR_MSG_WM_MOVE(OnMove)
CR_MSG_WM_MOVING(OnMoving)
CR_MSG_WM_NCCALCSIZE(OnNCCalcSize)
CR_MSG_WM_NCCREATE(OnNCCreate)
CR_MSG_WM_NCHITTEST(OnNCHitTest)
CR_MSG_WM_NCPAINT(OnNCPaint)
CR_MSG_WM_PAINT(OnPaint)
CR_MSG_WM_SETFOCUS(OnSetFocus)
CR_MSG_WM_SETICON(OnSetIcon)
CR_MSG_WM_SETTEXT(OnSetText)
CR_MSG_WM_SETTINGCHANGE(OnSettingChange)
CR_MSG_WM_SIZE(OnSize)
CR_MSG_WM_SIZING(OnSizing)
CR_MSG_WM_SYSCOMMAND(OnSysCommand)
CR_MSG_WM_THEMECHANGED(OnThemeChanged)
CR_MSG_WM_TIMECHANGE(OnTimeChange)
CR_MSG_WM_WINDOWPOSCHANGED(OnWindowPosChanged)
CR_MSG_WM_WINDOWPOSCHANGING(OnWindowPosChanging)
CR_END_MSG_MAP()
// Message Handlers.
// This list is in _ALPHABETICAL_ order!
// TODO(beng): Once this object becomes the WindowImpl, these methods can
// be made private.
void OnActivateApp(BOOL active, DWORD thread_id);
// TODO(beng): return BOOL is temporary until this object becomes a
// WindowImpl.
BOOL OnAppCommand(HWND window, int command, WORD device, WORD keystate);
void OnCancelMode();
void OnCaptureChanged(HWND window);
void OnClose();
void OnCommand(UINT notification_code, int command, HWND window);
LRESULT OnCreate(CREATESTRUCT* create_struct);
void OnDestroy();
void OnDisplayChange(UINT bits_per_pixel, const gfx::Size& screen_size);
LRESULT OnDpiChanged(UINT msg, WPARAM w_param, LPARAM l_param);
void OnEnterMenuLoop(BOOL from_track_popup_menu);
void OnEnterSizeMove();
LRESULT OnEraseBkgnd(HDC dc);
void OnExitMenuLoop(BOOL is_shortcut_menu);
void OnExitSizeMove();
void OnGetMinMaxInfo(MINMAXINFO* minmax_info);
LRESULT OnGetObject(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnImeMessages(UINT message, WPARAM w_param, LPARAM l_param);
void OnInitMenu(HMENU menu);
LRESULT OnInputEvent(UINT message, WPARAM w_param, LPARAM l_param);
void OnInputLangChange(DWORD character_set, HKL input_language_id);
LRESULT OnKeyEvent(UINT message, WPARAM w_param, LPARAM l_param);
void OnKillFocus(HWND focused_window);
LRESULT OnMouseActivate(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnMouseRange(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnPointerActivate(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnPointerEvent(UINT message, WPARAM w_param, LPARAM l_param);
void OnMove(const gfx::Point& point);
void OnMoving(UINT param, const RECT* new_bounds);
LRESULT OnNCActivate(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnNCCalcSize(BOOL mode, LPARAM l_param);
LRESULT OnNCCreate(LPCREATESTRUCT lpCreateStruct);
LRESULT OnNCHitTest(const gfx::Point& point);
void OnNCPaint(HRGN rgn);
LRESULT OnNCUAHDrawCaption(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnNCUAHDrawFrame(UINT message, WPARAM w_param, LPARAM l_param);
void OnPaint(HDC dc);
LRESULT OnReflectedMessage(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnScrollMessage(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnSetCursor(UINT message, WPARAM w_param, LPARAM l_param);
void OnSetFocus(HWND last_focused_window);
LRESULT OnSetIcon(UINT size_type, HICON new_icon);
LRESULT OnSetText(const wchar_t* text);
void OnSettingChange(UINT flags, const wchar_t* section);
void OnSize(UINT param, const gfx::Size& size);
void OnSizing(UINT param, RECT* rect);
void OnSysCommand(UINT notification_code, const gfx::Point& point);
void OnThemeChanged();
void OnTimeChange();
LRESULT OnTouchEvent(UINT message, WPARAM w_param, LPARAM l_param);
void OnWindowPosChanging(WINDOWPOS* window_pos);
void OnWindowPosChanged(WINDOWPOS* window_pos);
LRESULT OnWindowSizingFinished(UINT message, WPARAM w_param, LPARAM l_param);
// Receives Windows Session Change notifications.
void OnSessionChange(WPARAM status_code, const bool* is_current_session);
using TouchEvents = std::vector<ui::TouchEvent>;
// Helper to handle the list of touch events passed in. We need this because
// touch events on windows don't fire if we enter a modal loop in the context
// of a touch event.
void HandleTouchEvents(const TouchEvents& touch_events);
// Resets the flag which indicates that we are in the context of a touch down
// event.
void ResetTouchDownContext();
// Helper to handle mouse events.
// The |message|, |w_param|, |l_param| parameters identify the Windows mouse
// message and its parameters respectively.
// The |track_mouse| parameter indicates if we should track the mouse.
LRESULT HandleMouseEventInternal(UINT message,
WPARAM w_param,
LPARAM l_param,
bool track_mouse);
// We handle 2 kinds of WM_POINTER events: PT_TOUCH and PT_PEN. This helper
// handles client area events of PT_TOUCH, and non-client area events of both
// kinds.
LRESULT HandlePointerEventTypeTouchOrNonClient(UINT message,
WPARAM w_param,
LPARAM l_param);
// Helper to handle client area events of PT_PEN.
LRESULT HandlePointerEventTypePenClient(UINT message,
WPARAM w_param,
LPARAM l_param);
// Helper to handle client area events of PT_PEN.
LRESULT HandlePointerEventTypePen(UINT message,
UINT32 pointer_id,
POINTER_PEN_INFO pointer_pen_info);
// Returns true if the mouse message passed in is an OS synthesized mouse
// message.
// |message| identifies the mouse message.
// |message_time| is the time when the message occurred.
// |l_param| indicates the location of the mouse message.
bool IsSynthesizedMouseMessage(unsigned int message,
int message_time,
LPARAM l_param);
// Provides functionality to transition a frame to DWM.
void PerformDwmTransition();
// Updates DWM frame to extend into client area if needed.
void UpdateDwmFrame();
// Generates a touch event and adds it to the |touch_events| parameter.
// |point| is the point where the touch was initiated.
// |id| is the event id associated with the touch event.
// |time_stamp| is the time stamp associated with the message.
void GenerateTouchEvent(ui::EventType event_type,
const gfx::Point& point,
ui::PointerId id,
base::TimeTicks time_stamp,
TouchEvents* touch_events);
// Handles WM_NCLBUTTONDOWN and WM_NCMOUSEMOVE messages on the caption.
// Returns true if the message was handled.
bool HandleMouseInputForCaption(unsigned int message,
WPARAM w_param,
LPARAM l_param);
// Helper function for setting the bounds of the HWND. For more information
// please refer to the SetBounds() function.
void SetBoundsInternal(const gfx::Rect& bounds_in_pixels,
bool force_size_changed);
// Checks if there is a full screen window on the same monitor as the
// |window| which is becoming active. If yes then we reduce the size of the
// fullscreen window by 1 px to ensure that maximized windows on the same
// monitor don't draw over the taskbar.
void CheckAndHandleBackgroundFullscreenOnMonitor(HWND window);
// Provides functionality to reduce the bounds of the fullscreen window by 1
// px on activation loss to a window on the same monitor.
void OnBackgroundFullscreen();
// Deletes the system caret used for accessibility. This will result in any
// clients that are still holding onto its |IAccessible| to get a failure code
// if they request its location.
void DestroyAXSystemCaret();
// Updates |rect| to adhere to the |aspect_ratio| of the window. |param|
// refers to the edge of the window being sized.
void SizeWindowToAspectRatio(UINT param, gfx::Rect* rect);
// Get the cursor position, which may be mocked if running a test
POINT GetCursorPos() const;
// Sets headless window bounds which may be different from the platform window
// bounds and updates Aura window property that stores headless window bounds
// for upper layers to retrieve.
void SetHeadlessWindowBounds(const gfx::Rect& bounds);
raw_ptr<HWNDMessageHandlerDelegate> delegate_;
std::unique_ptr<FullscreenHandler> fullscreen_handler_;
// Set to true in Close() and false is CloseNow().
bool waiting_for_close_now_;
bool use_system_default_icon_;
// Whether all ancestors have been enabled. This is only used if is_modal_ is
// true.
bool restored_enabled_;
// The current cursor.
scoped_refptr<ui::WinCursor> current_cursor_;
// The icon created from the bitmap image of the window icon.
base::win::ScopedHICON window_icon_;
// The icon created from the bitmap image of the app icon.
base::win::ScopedHICON app_icon_;
// The aspect ratio for the window. This is only used for sizing operations
// for the non-client area.
absl::optional<float> aspect_ratio_;
// Size to exclude from aspect ratio calculation.
gfx::Size excluded_margin_;
// The current DPI.
int dpi_;
// This is true if the window is created with a specific size/location, as
// opposed to having them set after window creation.
bool initial_bounds_valid_ = false;
// Whether EnableNonClientDpiScaling was called successfully with this window.
// This flag exists because EnableNonClientDpiScaling must be called during
// WM_NCCREATE and EnableChildWindowDpiMessage is called after window
// creation. We don't want to call both, so this helps us determine if a call
// to EnableChildWindowDpiMessage is necessary.
bool called_enable_non_client_dpi_scaling_;
// Event handling ------------------------------------------------------------
// The flags currently being used with TrackMouseEvent to track mouse
// messages. 0 if there is no active tracking. The value of this member is
// used when tracking is canceled.
DWORD active_mouse_tracking_flags_;
// Set to true when the user presses the right mouse button on the caption
// area. We need this so we can correctly show the context menu on mouse-up.
bool is_right_mouse_pressed_on_caption_;
// The set of touch devices currently down.
TouchIDs touch_ids_;
// ScopedRedrawLock ----------------------------------------------------------
// Represents the number of ScopedRedrawLocks active against this widget.
// If this is greater than zero, the widget should be locked against updates.
int lock_updates_count_;
// Window resizing -----------------------------------------------------------
// When true, this flag makes us discard incoming SetWindowPos() requests that
// only change our position/size. (We still allow changes to Z-order,
// activation, etc.)
bool ignore_window_pos_changes_;
// Keeps track of the last size type param received from a WM_SIZE message.
UINT last_size_param_ = SIZE_RESTORED;
// The last-seen monitor containing us, and its rect and work area. These are
// used to catch updates to the rect and work area and react accordingly.
HMONITOR last_monitor_;
gfx::Rect last_monitor_rect_, last_work_area_;
// True the first time nccalc is called on a sizable widget
bool is_first_nccalc_;
// Copy of custom window region specified via SetRegion(), if any.
base::win::ScopedRegion custom_window_region_;
// If > 0 indicates a menu is running (we're showing a native menu).
int menu_depth_;
// Generates touch-ids for touch-events.
ui::SequentialIDGenerator id_generator_;
PenEventProcessor pen_processor_;
// Stores a pointer to the WindowEventTarget interface implemented by this
// class. Allows callers to retrieve the interface pointer.
std::unique_ptr<ui::ViewProp> prop_window_target_;
// Number of active touch down contexts. This is incremented on touch down
// events and decremented later using a delayed task.
// We need this to ignore WM_MOUSEACTIVATE messages generated in response to
// touch input. This is fine because activation still works correctly via
// native SetFocus calls invoked in the views code.
int touch_down_contexts_;
// Time the last touch or pen message was received. Used to flag mouse
// messages synthesized by Windows for touch which are not flagged by the OS
// as synthesized mouse messages. For more information please refer to the
// IsMouseEventFromTouch function.
static LONG last_touch_or_pen_message_time_;
// When true, this flag makes us discard window management mouse messages.
// Windows sends window management mouse messages at the mouse location when
// window states change (e.g. tooltips or status bubbles opening/closing).
// Those system generated messages should be ignored while the pen is active
// over the client area, where it is not in sync with the mouse position.
// Reset to false when we get user mouse input again.
static bool is_pen_active_in_client_area_;
// Time the last WM_MOUSEHWHEEL message is received. Please refer to the
// HandleMouseEventInternal function as to why this is needed.
LONG last_mouse_hwheel_time_;
// On Windows Vista and beyond, if we are transitioning from custom frame
// to Aero(glass) we delay setting the DWM related properties in full
// screen mode as DWM is not supported in full screen windows. We perform
// the DWM related operations when the window comes out of fullscreen mode.
// This member variable is set to true if the window is transitioning to
// glass. Defaults to false.
bool dwm_transition_desired_;
// True if HandleWindowSizeChanging has been called in the delegate, but not
// HandleClientSizeChanged.
bool sent_window_size_changing_;
// This is used to keep track of whether a WM_WINDOWPOSCHANGED has
// been received after the WM_WINDOWPOSCHANGING.
uint32_t current_window_size_message_ = 0;
// Manages observation of Windows Session Change messages.
std::unique_ptr<ui::SessionChangeObserver> session_change_observer_;
// Some assistive software need to track the location of the caret.
std::unique_ptr<ui::AXSystemCaretWin> ax_system_caret_;
// Implements IRawElementProviderFragmentRoot when UIA is enabled.
std::unique_ptr<ui::AXFragmentRootWin> ax_fragment_root_;
// Set to true when we return a UIA object. Determines whether we need to
// call UIA to clean up object references on window destruction.
// This is important to avoid triggering a cross-thread COM call which could
// cause re-entrancy during teardown. https://crbug.com/1087553
bool did_return_uia_object_;
// The location where the user clicked on the caption. We cache this when we
// receive the WM_NCLBUTTONDOWN message. We use this in the subsequent
// WM_NCMOUSEMOVE message to see if the mouse actually moved.
// Please refer to the HandleMouseEventInternal function for details on why
// this is needed.
gfx::Point caption_left_button_click_pos_;
// Set to true if the left mouse button has been pressed on the caption.
// Defaults to false.
bool left_button_down_on_caption_;
// Set to true if the window is a background fullscreen window, i.e a
// fullscreen window which lost activation. Defaults to false.
bool background_fullscreen_hack_;
// True if the window should have no border and its contents should be
// partially or fully transparent.
bool is_translucent_ = false;
// True if the window should process WM_POINTER for touch events and
// not WM_TOUCH events.
bool pointer_events_for_touch_;
// True if DWM frame should be cleared on next WM_ERASEBKGND message. This is
// necessary to avoid white flashing in the titlebar area around the
// minimize/maximize/close buttons. Clearing the frame on every WM_ERASEBKGND
// message causes black flickering in the titlebar region so we do it on for
// the first message after frame type changes.
bool needs_dwm_frame_clear_ = true;
// True if is handling mouse WM_INPUT messages.
bool using_wm_input_ = false;
// True if we're displaying the system menu on the title bar. If we are,
// then we want to ignore right mouse clicks instead of bringing up a
// context menu.
bool handling_mouse_menu_ = false;
// This is set to true when we call ShowWindow(SC_RESTORE), in order to
// call HandleWindowMinimizedOrRestored() when we get a WM_ACTIVATE message.
bool notify_restore_on_activate_ = false;
// Counts the number of drag events received after a drag started event.
// This will be used to ignore a drag event to 0, 0, if it is one of the
// first few drag events after a drag started event. We randomly receive
// bogus 0, 0 drag events after the start of a drag. See
// https://crbug.com/1270828.
int num_drag_events_after_press_ = 0;
// Records ::GetLastError when ::ReleaseCapture fails. Logged in the DCHECK
// in `SetCapture` to diagnose https://crbug.com/1386013.
DWORD release_capture_errno_ = 0;
// This tracks headless window visibility, fullscreen and min/max states. In
// headless mode the platform window is never made visible or change its
// state, so this structure holds the requested state for reporting.
struct HeadlessModeWindow {
bool IsMinimized() const { return minmax_state == kMinimized; }
bool IsMaximized() const { return minmax_state == kMaximized; }
bool visibility_state = false;
bool fullscreen_state = false;
bool active_state = false;
enum { kNormal, kMinimized, kMaximized } minmax_state = kNormal;
gfx::Rect bounds;
};
// This is present iff the window has been created in headless mode.
absl::optional<HeadlessModeWindow> headless_mode_window_;
// This is a map of the HMONITOR to full screeen window instance. It is safe
// to keep a raw pointer to the HWNDMessageHandler instance as we track the
// window destruction and ensure that the map is cleaned up.
using FullscreenWindowMonitorMap = std::map<HMONITOR, HWNDMessageHandler*>;
static base::LazyInstance<FullscreenWindowMonitorMap>::DestructorAtExit
fullscreen_monitor_map_;
// How many pixels the window is expected to grow from OnWindowPosChanging().
// Used to fill the newly exposed pixels black in OnPaint() before the
// browser compositor is able to redraw at the new window size.
gfx::Size exposed_pixels_;
// Populated if the cursor position is being mocked for testing purposes.
absl::optional<gfx::Point> mock_cursor_position_;
base::ScopedObservation<ui::InputMethod, ui::InputMethodObserver>
observation_{this};
// The WeakPtrFactories below (one inside the
// CR_MSG_MAP_CLASS_DECLARATIONS macro and autohide_factory_) must
// occur last in the class definition so they get destroyed last.
CR_MSG_MAP_CLASS_DECLARATIONS(HWNDMessageHandler)
// The factory used to lookup appbar autohide edges.
base::WeakPtrFactory<HWNDMessageHandler> autohide_factory_{this};
};
} // namespace views
#endif // UI_VIEWS_WIN_HWND_MESSAGE_HANDLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/win/hwnd_message_handler.h | C++ | unknown | 36,399 |
// 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_WIN_HWND_MESSAGE_HANDLER_DELEGATE_H_
#define UI_VIEWS_WIN_HWND_MESSAGE_HANDLER_DELEGATE_H_
#include "base/win/windows_types.h"
#include "ui/base/ui_base_types.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/views_export.h"
class SkPath;
namespace gfx {
class Insets;
class Point;
class Rect;
class Size;
} // namespace gfx
namespace ui {
class Accelerator;
class InputMethod;
class KeyEvent;
class MouseEvent;
class ScrollEvent;
class TouchEvent;
class GestureEvent;
} // namespace ui
namespace views {
enum class FrameMode {
SYSTEM_DRAWN, // "glass" frame
SYSTEM_DRAWN_NO_CONTROLS, // "glass" frame but with custom window controls
CUSTOM_DRAWN // "opaque" frame
};
// Implemented by the object that uses the HWNDMessageHandler to handle
// notifications from the underlying HWND and service requests for data.
class VIEWS_EXPORT HWNDMessageHandlerDelegate {
public:
// Returns the input method currently used in this window.
virtual ui::InputMethod* GetHWNDMessageDelegateInputMethod() = 0;
// True if the widget associated with this window has a non-client view.
virtual bool HasNonClientView() const = 0;
// Returns who we want to be drawing the frame. Either the system (Windows)
// will handle it or Chrome will custom draw it.
virtual FrameMode GetFrameMode() const = 0;
// True if a frame should be drawn. This will return true for some windows
// that don't have a visible frame. Those usually have the WS_POPUP style, for
// which Windows will remove the frame automatically if the frame mode is
// SYSTEM_DRAWN.
// TODO(bsep): Investigate deleting this when v2 Apps support is removed.
virtual bool HasFrame() const = 0;
// True if the window should paint as active (regardless of whether it has
// system focus).
virtual bool ShouldPaintAsActive() const = 0;
virtual void SchedulePaint() = 0;
virtual bool CanResize() const = 0;
virtual bool CanMaximize() const = 0;
virtual bool CanMinimize() const = 0;
virtual bool CanActivate() const = 0;
// Returns true if the delegate wants mouse events when inactive and the
// window is clicked and should not become activated. A return value of false
// indicates the mouse events will be dropped.
virtual bool WantsMouseEventsWhenInactive() const = 0;
virtual bool WidgetSizeIsClientSize() const = 0;
// Returns true if the delegate represents a modal window.
virtual bool IsModal() const = 0;
// Returns the show state that should be used for the application's first
// window.
virtual int GetInitialShowState() const = 0;
virtual int GetNonClientComponent(const gfx::Point& point) const = 0;
virtual void GetWindowMask(const gfx::Size& size, SkPath* mask) = 0;
// Returns true if the delegate modifies |insets| to define a custom client
// area for the window, false if the default client area should be used. If
// false is returned, |insets| is not modified. |monitor| is the monitor
// this window is on. Normally that would be determined from the HWND, but
// during WM_NCCALCSIZE Windows does not return the correct monitor for the
// HWND, so it must be passed in explicitly (see HWNDMessageHandler::
// OnNCCalcSize for more details).
virtual bool GetClientAreaInsets(gfx::Insets* insets,
HMONITOR monitor) const = 0;
// Returns true if DWM frame should be extended into client area by |insets|.
// Insets are specified in screen pixels not DIP because that's what DWM uses.
virtual bool GetDwmFrameInsetsInPixels(gfx::Insets* insets) const = 0;
// Returns the minimum and maximum size the window can be resized to by the
// user.
virtual void GetMinMaxSize(gfx::Size* min_size,
gfx::Size* max_size) const = 0;
// Returns the current size of the RootView.
virtual gfx::Size GetRootViewSize() const = 0;
virtual gfx::Size DIPToScreenSize(const gfx::Size& dip_size) const = 0;
virtual void ResetWindowControls() = 0;
virtual gfx::NativeViewAccessible GetNativeViewAccessible() = 0;
// TODO(beng): Investigate migrating these methods to On* prefixes once
// HWNDMessageHandler is the WindowImpl.
// Called when the window was activated or deactivated. |active| reflects the
// new state.
virtual void HandleActivationChanged(bool active) = 0;
// Called when a well known "app command" from the system was performed.
// Returns true if the command was handled.
virtual bool HandleAppCommand(int command) = 0;
// Called from WM_CANCELMODE.
virtual void HandleCancelMode() = 0;
// Called when the window has lost mouse capture.
virtual void HandleCaptureLost() = 0;
// Called when the user tried to close the window.
virtual void HandleClose() = 0;
// Called when a command defined by the application was performed. Returns
// true if the command was handled.
virtual bool HandleCommand(int command) = 0;
// Called when an accelerator is invoked.
virtual void HandleAccelerator(const ui::Accelerator& accelerator) = 0;
// Called when the HWND is created.
virtual void HandleCreate() = 0;
// Called when the HWND is being destroyed, before any child HWNDs are
// destroyed.
virtual void HandleDestroying() = 0;
// Called after the HWND is destroyed, after all child HWNDs have been
// destroyed.
virtual void HandleDestroyed() = 0;
// Called when the HWND is to be focused for the first time. This is called
// when the window is shown for the first time. Returns true if the delegate
// set focus and no default processing should be done by the message handler.
virtual bool HandleInitialFocus(ui::WindowShowState show_state) = 0;
// Called when display settings are adjusted on the system.
virtual void HandleDisplayChange() = 0;
// Called when the user begins or ends a size/move operation using the window
// manager.
virtual void HandleBeginWMSizeMove() = 0;
virtual void HandleEndWMSizeMove() = 0;
// Called when the window's position changed.
virtual void HandleMove() = 0;
// Called when the system's work area has changed.
virtual void HandleWorkAreaChanged() = 0;
// Called when the window's visibility changed. |visible| holds the new state.
virtual void HandleVisibilityChanged(bool visible) = 0;
// Called when a top level window is minimized or restored.
virtual void HandleWindowMinimizedOrRestored(bool restored) = 0;
// Called when the window's client size changed. |new_size| holds the new
// size.
virtual void HandleClientSizeChanged(const gfx::Size& new_size) = 0;
// Called when the window's frame has changed.
virtual void HandleFrameChanged() = 0;
// Called when focus shifted to this HWND from |last_focused_window|.
virtual void HandleNativeFocus(HWND last_focused_window) = 0;
// Called when focus shifted from the HWND to a different window.
virtual void HandleNativeBlur(HWND focused_window) = 0;
// Called when a mouse event is received. Returns true if the event was
// handled by the delegate.
virtual bool HandleMouseEvent(ui::MouseEvent* event) = 0;
// Called when an untranslated key event is received (i.e. pre-IME
// translation).
virtual void HandleKeyEvent(ui::KeyEvent* event) = 0;
// Called when a touch event is received.
virtual void HandleTouchEvent(ui::TouchEvent* event) = 0;
// Called when an IME message needs to be processed by the delegate. Returns
// true if the event was handled and no default processing should be
// performed.
virtual bool HandleIMEMessage(UINT message,
WPARAM w_param,
LPARAM l_param,
LRESULT* result) = 0;
// Called when the system input language changes.
virtual void HandleInputLanguageChange(DWORD character_set,
HKL input_language_id) = 0;
// Called to compel the delegate to paint |invalid_rect| accelerated.
virtual void HandlePaintAccelerated(const gfx::Rect& invalid_rect) = 0;
// Invoked on entering/exiting a menu loop.
virtual void HandleMenuLoop(bool in_menu_loop) = 0;
// Catch-all message handling and filtering. Called before
// HWNDMessageHandler's built-in handling, which may pre-empt some
// expectations in Views/Aura if messages are consumed. Returns true if the
// message was consumed by the delegate and should not be processed further
// by the HWNDMessageHandler. In this case, |result| is returned. |result| is
// not modified otherwise.
virtual bool PreHandleMSG(UINT message,
WPARAM w_param,
LPARAM l_param,
LRESULT* result) = 0;
// Like PreHandleMSG, but called after HWNDMessageHandler's built-in handling
// has run and after DefWindowProc.
virtual void PostHandleMSG(UINT message, WPARAM w_param, LPARAM l_param) = 0;
// Called when a scroll event is received. Returns true if the event was
// handled by the delegate.
virtual bool HandleScrollEvent(ui::ScrollEvent* event) = 0;
// Called when a gesture event is received. Returns true if the event was
// handled by the delegate.
virtual bool HandleGestureEvent(ui::GestureEvent* event) = 0;
// Called when the window size is about to change.
virtual void HandleWindowSizeChanging() = 0;
// Called after HandleWindowSizeChanging() when it's determined the window
// size didn't actually change.
virtual void HandleWindowSizeUnchanged() = 0;
// Called when the window scale factor has changed.
virtual void HandleWindowScaleFactorChanged(float window_scale_factor) = 0;
// Called when the headless window bounds has changed.
virtual void HandleHeadlessWindowBoundsChanged(const gfx::Rect& bounds) = 0;
protected:
virtual ~HWNDMessageHandlerDelegate() = default;
};
} // namespace views
#endif // UI_VIEWS_WIN_HWND_MESSAGE_HANDLER_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/win/hwnd_message_handler_delegate.h | C++ | unknown | 10,123 |
// 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_WIN_HWND_UTIL_H_
#define UI_VIEWS_WIN_HWND_UTIL_H_
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/views_export.h"
namespace views {
class View;
class Widget;
// Returns the HWND for the specified View.
VIEWS_EXPORT HWND HWNDForView(const View* view);
// Returns the HWND for the specified Widget.
VIEWS_EXPORT HWND HWNDForWidget(const Widget* widget);
// Returns the HWND for the specified NativeView.
VIEWS_EXPORT HWND HWNDForNativeView(const gfx::NativeView view);
// Returns the HWND for the specified NativeWindow.
VIEWS_EXPORT HWND HWNDForNativeWindow(const gfx::NativeWindow window);
VIEWS_EXPORT gfx::Rect GetWindowBoundsForClientBounds(
View* view,
const gfx::Rect& client_bounds);
// Shows |window|'s system menu (at a specified |point| in screen physical
// coordinates).
VIEWS_EXPORT void ShowSystemMenuAtScreenPixelLocation(HWND window,
const gfx::Point& point);
} // namespace views
#endif // UI_VIEWS_WIN_HWND_UTIL_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/win/hwnd_util.h | C++ | unknown | 1,249 |
// 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/win/hwnd_util.h"
#include <windows.h>
#include "base/i18n/rtl.h"
#include "base/trace_event/base_tracing.h"
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/views/widget/widget.h"
namespace views {
HWND HWNDForView(const View* view) {
return view->GetWidget() ? HWNDForWidget(view->GetWidget()) : nullptr;
}
HWND HWNDForWidget(const Widget* widget) {
return HWNDForNativeWindow(widget->GetNativeWindow());
}
HWND HWNDForNativeView(const gfx::NativeView view) {
return view && view->GetRootWindow() ? view->GetHost()->GetAcceleratedWidget()
: nullptr;
}
HWND HWNDForNativeWindow(const gfx::NativeWindow window) {
return window && window->GetRootWindow()
? window->GetHost()->GetAcceleratedWidget()
: nullptr;
}
gfx::Rect GetWindowBoundsForClientBounds(View* view,
const gfx::Rect& client_bounds) {
DCHECK(view);
aura::WindowTreeHost* host = view->GetWidget()->GetNativeWindow()->GetHost();
if (host) {
HWND hwnd = host->GetAcceleratedWidget();
RECT rect = client_bounds.ToRECT();
auto style = static_cast<DWORD>(::GetWindowLong(hwnd, GWL_STYLE));
auto ex_style = static_cast<DWORD>(::GetWindowLong(hwnd, GWL_EXSTYLE));
::AdjustWindowRectEx(&rect, style, FALSE, ex_style);
return gfx::Rect(rect);
}
return client_bounds;
}
void ShowSystemMenuAtScreenPixelLocation(HWND window, const gfx::Point& point) {
TRACE_EVENT0("ui", "ShowSystemMenuAtScreenPixelLocation");
UINT flags = TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD;
if (base::i18n::IsRTL())
flags |= TPM_RIGHTALIGN;
HMENU menu = ::GetSystemMenu(window, FALSE);
const int command =
::TrackPopupMenu(menu, flags, point.x(), point.y(), 0, window, nullptr);
if (command)
::SendMessage(window, WM_SYSCOMMAND, static_cast<WPARAM>(command), 0);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/win/hwnd_util_aurawin.cc | C++ | unknown | 2,114 |
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/win/pen_event_processor.h"
#include "base/check.h"
#include "base/notreached.h"
#include "base/time/time.h"
#include "ui/events/event_constants.h"
#include "ui/events/event_utils.h"
namespace views {
namespace {
int GetFlagsFromPointerMessage(UINT message, const POINTER_INFO& pointer_info) {
int flags = ui::EF_NONE;
if (pointer_info.pointerFlags & POINTER_FLAG_FIRSTBUTTON)
flags |= ui::EF_LEFT_MOUSE_BUTTON;
if (pointer_info.pointerFlags & POINTER_FLAG_SECONDBUTTON)
flags |= ui::EF_RIGHT_MOUSE_BUTTON;
return flags;
}
} // namespace
PenEventProcessor::PenEventProcessor(ui::SequentialIDGenerator* id_generator,
bool direct_manipulation_enabled)
: id_generator_(id_generator),
direct_manipulation_enabled_(direct_manipulation_enabled) {}
PenEventProcessor::~PenEventProcessor() = default;
std::unique_ptr<ui::Event> PenEventProcessor::GenerateEvent(
UINT message,
UINT32 pointer_id,
const POINTER_PEN_INFO& pointer_pen_info,
const gfx::Point& point) {
auto mapped_pointer_id =
static_cast<ui::PointerId>(id_generator_->GetGeneratedID(pointer_id));
// We are now creating a fake mouse event with pointer type of pen from
// the WM_POINTER message and then setting up an associated pointer
// details in the MouseEvent which contains the pen's information.
ui::EventPointerType input_type = ui::EventPointerType::kPen;
// For the pointerup event, the penFlags is not set to PEN_FLAG_ERASER, so we
// have to check if previously the pointer type is an eraser.
if (pointer_pen_info.penFlags & PEN_FLAG_ERASER) {
input_type = ui::EventPointerType::kEraser;
DCHECK(!eraser_pointer_id_ || *eraser_pointer_id_ == mapped_pointer_id);
eraser_pointer_id_ = mapped_pointer_id;
} else if (eraser_pointer_id_ && *eraser_pointer_id_ == mapped_pointer_id &&
(message == WM_POINTERUP || message == WM_NCPOINTERUP)) {
input_type = ui::EventPointerType::kEraser;
eraser_pointer_id_.reset();
}
// convert pressure into a float [0, 1]. The range of the pressure is
// [0, 1024] as specified on MSDN.
float pressure = static_cast<float>(pointer_pen_info.pressure) / 1024;
int rotation_angle = static_cast<int>(pointer_pen_info.rotation) % 180;
if (rotation_angle < 0)
rotation_angle += 180;
int tilt_x = pointer_pen_info.tiltX;
int tilt_y = pointer_pen_info.tiltY;
ui::PointerDetails pointer_details(
input_type, mapped_pointer_id, /* radius_x */ 0.0f, /* radius_y */ 0.0f,
pressure, rotation_angle, tilt_x, tilt_y, /* tangential_pressure */ 0.0f);
int32_t device_id = pen_id_handler_.TryGetPenUniqueId(pointer_id)
.value_or(ui::ED_UNKNOWN_DEVICE);
// If the flag is disabled, we send mouse events for all pen inputs.
if (!direct_manipulation_enabled_) {
return GenerateMouseEvent(message, pointer_id, pointer_pen_info.pointerInfo,
point, pointer_details, device_id);
}
bool is_pointer_event =
message == WM_POINTERENTER || message == WM_POINTERLEAVE;
// Send MouseEvents when the pen is hovering or any buttons (other than the
// tip) are depressed when the stylus makes contact with the digitizer. Ensure
// we read |send_touch_for_pen_| before we process the event as we want to
// ensure a TouchRelease is sent appropriately at the end when the stylus is
// no longer in contact with the digitizer.
bool send_touch = send_touch_for_pen_.count(pointer_id) == 0
? false
: send_touch_for_pen_[pointer_id];
if (pointer_pen_info.pointerInfo.pointerFlags & POINTER_FLAG_INCONTACT) {
if (!pen_in_contact_[pointer_id]) {
send_touch = send_touch_for_pen_[pointer_id] =
(pointer_pen_info.pointerInfo.pointerFlags &
(POINTER_FLAG_SECONDBUTTON | POINTER_FLAG_THIRDBUTTON |
POINTER_FLAG_FOURTHBUTTON | POINTER_FLAG_FIFTHBUTTON)) == 0;
}
pen_in_contact_[pointer_id] = true;
} else {
pen_in_contact_.erase(pointer_id);
send_touch_for_pen_.erase(pointer_id);
}
if (is_pointer_event || !send_touch) {
return GenerateMouseEvent(message, pointer_id, pointer_pen_info.pointerInfo,
point, pointer_details, device_id);
}
return GenerateTouchEvent(message, pointer_id, pointer_pen_info.pointerInfo,
point, pointer_details, device_id);
}
std::unique_ptr<ui::Event> PenEventProcessor::GenerateMouseEvent(
UINT message,
UINT32 pointer_id,
const POINTER_INFO& pointer_info,
const gfx::Point& point,
const ui::PointerDetails& pointer_details,
int32_t device_id) {
ui::EventType event_type = ui::ET_MOUSE_MOVED;
int flag = GetFlagsFromPointerMessage(message, pointer_info);
int changed_flag = ui::EF_NONE;
int click_count = 0;
switch (message) {
case WM_POINTERDOWN:
case WM_NCPOINTERDOWN:
event_type = ui::ET_MOUSE_PRESSED;
if (pointer_info.ButtonChangeType == POINTER_CHANGE_FIRSTBUTTON_DOWN)
changed_flag = ui::EF_LEFT_MOUSE_BUTTON;
else
changed_flag = ui::EF_RIGHT_MOUSE_BUTTON;
click_count = 1;
sent_mouse_down_[pointer_id] = true;
break;
case WM_POINTERUP:
case WM_NCPOINTERUP:
event_type = ui::ET_MOUSE_RELEASED;
if (pointer_info.ButtonChangeType == POINTER_CHANGE_FIRSTBUTTON_UP) {
flag |= ui::EF_LEFT_MOUSE_BUTTON;
changed_flag = ui::EF_LEFT_MOUSE_BUTTON;
} else {
flag |= ui::EF_RIGHT_MOUSE_BUTTON;
changed_flag = ui::EF_RIGHT_MOUSE_BUTTON;
}
id_generator_->ReleaseNumber(pointer_id);
click_count = 1;
if (sent_mouse_down_.count(pointer_id) == 0 ||
!sent_mouse_down_[pointer_id])
return nullptr;
sent_mouse_down_[pointer_id] = false;
break;
case WM_POINTERUPDATE:
case WM_NCPOINTERUPDATE:
event_type = ui::ET_MOUSE_DRAGGED;
if (flag == ui::EF_NONE)
event_type = ui::ET_MOUSE_MOVED;
break;
case WM_POINTERENTER:
event_type = ui::ET_MOUSE_ENTERED;
break;
case WM_POINTERLEAVE:
event_type = ui::ET_MOUSE_EXITED;
id_generator_->ReleaseNumber(pointer_id);
break;
default:
NOTREACHED_NORETURN();
}
std::unique_ptr<ui::Event> event = std::make_unique<ui::MouseEvent>(
event_type, point, point, ui::EventTimeForNow(),
flag | ui::GetModifiersFromKeyState(), changed_flag, pointer_details);
event->AsMouseEvent()->SetClickCount(click_count);
event->set_source_device_id(device_id);
return event;
}
std::unique_ptr<ui::Event> PenEventProcessor::GenerateTouchEvent(
UINT message,
UINT32 pointer_id,
const POINTER_INFO& pointer_info,
const gfx::Point& point,
const ui::PointerDetails& pointer_details,
int32_t device_id) {
int flags = GetFlagsFromPointerMessage(message, pointer_info);
ui::EventType event_type = ui::ET_TOUCH_MOVED;
switch (message) {
case WM_POINTERDOWN:
case WM_NCPOINTERDOWN:
event_type = ui::ET_TOUCH_PRESSED;
sent_touch_start_[pointer_id] = true;
break;
case WM_POINTERUP:
case WM_NCPOINTERUP:
event_type = ui::ET_TOUCH_RELEASED;
id_generator_->ReleaseNumber(pointer_id);
if (sent_touch_start_.count(pointer_id) == 0 ||
!sent_touch_start_[pointer_id])
return nullptr;
sent_touch_start_[pointer_id] = false;
break;
case WM_POINTERUPDATE:
case WM_NCPOINTERUPDATE:
event_type = ui::ET_TOUCH_MOVED;
break;
default:
NOTREACHED_NORETURN();
}
const base::TimeTicks event_time = ui::EventTimeForNow();
std::unique_ptr<ui::TouchEvent> event = std::make_unique<ui::TouchEvent>(
event_type, point, event_time, pointer_details,
flags | ui::GetModifiersFromKeyState());
ui::ComputeEventLatencyOSFromPOINTER_INFO(event_type, pointer_info,
event_time);
event->set_hovering(event_type == ui::ET_TOUCH_RELEASED);
event->latency()->AddLatencyNumberWithTimestamp(
ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT, event_time);
event->set_source_device_id(device_id);
return event;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/win/pen_event_processor.cc | C++ | unknown | 8,411 |
// 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_WIN_PEN_EVENT_PROCESSOR_H_
#define UI_VIEWS_WIN_PEN_EVENT_PROCESSOR_H_
#include <windows.h>
#include <memory>
#include "base/memory/raw_ptr.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/events/event.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/sequential_id_generator.h"
#include "ui/views/views_export.h"
#include "ui/views/win/pen_id_handler.h"
namespace views {
// This class handles the processing pen event state information
// from native Windows events and returning appropriate
// ui::Events for the current state.
class VIEWS_EXPORT PenEventProcessor {
public:
// |id_generator| must outlive this object's lifecycle.
PenEventProcessor(ui::SequentialIDGenerator* id_generator,
bool direct_manipulation_enabled);
PenEventProcessor(const PenEventProcessor&) = delete;
PenEventProcessor& operator=(const PenEventProcessor&) = delete;
~PenEventProcessor();
// Generate an appropriate ui::Event for a given pen pointer.
// May return nullptr if no event should be dispatched.
std::unique_ptr<ui::Event> GenerateEvent(
UINT message,
UINT32 pointer_id,
const POINTER_PEN_INFO& pen_pointer_info,
const gfx::Point& point);
private:
std::unique_ptr<ui::Event> GenerateMouseEvent(
UINT message,
UINT32 pointer_id,
const POINTER_INFO& pointer_info,
const gfx::Point& point,
const ui::PointerDetails& pointer_details,
int32_t device_id);
std::unique_ptr<ui::Event> GenerateTouchEvent(
UINT message,
UINT32 pointer_id,
const POINTER_INFO& pointer_info,
const gfx::Point& point,
const ui::PointerDetails& pointer_details,
int32_t device_id);
raw_ptr<ui::SequentialIDGenerator> id_generator_;
bool direct_manipulation_enabled_;
base::flat_map<UINT32, bool> pen_in_contact_;
base::flat_map<UINT32, bool> send_touch_for_pen_;
// There may be more than one pen used at the same time.
base::flat_map<UINT32, bool> sent_mouse_down_;
base::flat_map<UINT32, bool> sent_touch_start_;
absl::optional<ui::PointerId> eraser_pointer_id_;
PenIdHandler pen_id_handler_;
};
} // namespace views
#endif // UI_VIEWS_WIN_PEN_EVENT_PROCESSOR_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/win/pen_event_processor.h | C++ | unknown | 2,388 |
// 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/win/pen_event_processor.h"
#include "base/win/scoped_winrt_initializer.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/sequential_id_generator.h"
namespace views {
class PenProcessorTest : public ::testing::Test {
public:
PenProcessorTest() = default;
~PenProcessorTest() override = default;
// testing::Test overrides.
void SetUp() override;
private:
base::win::ScopedWinrtInitializer scoped_winrt_initializer_;
};
void PenProcessorTest::SetUp() {
ASSERT_TRUE(scoped_winrt_initializer_.Succeeded());
}
TEST_F(PenProcessorTest, TypicalCaseDMDisabled) {
ui::SequentialIDGenerator id_generator(0);
PenEventProcessor processor(&id_generator,
/*direct_manipulation_enabled*/ false);
POINTER_PEN_INFO pen_info;
memset(&pen_info, 0, sizeof(POINTER_PEN_INFO));
gfx::Point point(100, 100);
std::unique_ptr<ui::Event> event =
processor.GenerateEvent(WM_POINTERENTER, 0, pen_info, point);
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsMouseEvent());
EXPECT_EQ(ui::ET_MOUSE_ENTERED, event->AsMouseEvent()->type());
pen_info.pointerInfo.pointerFlags =
POINTER_FLAG_INCONTACT | POINTER_FLAG_FIRSTBUTTON;
pen_info.pointerInfo.ButtonChangeType = POINTER_CHANGE_FIRSTBUTTON_DOWN;
event = processor.GenerateEvent(WM_POINTERDOWN, 0, pen_info, point);
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsMouseEvent());
EXPECT_EQ(ui::ET_MOUSE_PRESSED, event->AsMouseEvent()->type());
EXPECT_EQ(1, event->AsMouseEvent()->GetClickCount());
EXPECT_EQ(ui::EF_LEFT_MOUSE_BUTTON,
event->AsMouseEvent()->changed_button_flags());
pen_info.pointerInfo.ButtonChangeType = POINTER_CHANGE_NONE;
event = processor.GenerateEvent(WM_POINTERUPDATE, 0, pen_info, point);
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsMouseEvent());
EXPECT_EQ(ui::ET_MOUSE_DRAGGED, event->AsMouseEvent()->type());
pen_info.pointerInfo.pointerFlags = POINTER_FLAG_INCONTACT;
pen_info.pointerInfo.ButtonChangeType = POINTER_CHANGE_FIRSTBUTTON_UP;
event = processor.GenerateEvent(WM_POINTERUP, 0, pen_info, point);
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsMouseEvent());
EXPECT_EQ(ui::ET_MOUSE_RELEASED, event->AsMouseEvent()->type());
EXPECT_EQ(ui::EF_LEFT_MOUSE_BUTTON,
event->AsMouseEvent()->changed_button_flags());
pen_info.pointerInfo.pointerFlags = POINTER_FLAG_NONE;
event = processor.GenerateEvent(WM_POINTERUPDATE, 0, pen_info, point);
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsMouseEvent());
EXPECT_EQ(ui::ET_MOUSE_MOVED, event->AsMouseEvent()->type());
event = processor.GenerateEvent(WM_POINTERLEAVE, 0, pen_info, point);
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsMouseEvent());
EXPECT_EQ(ui::ET_MOUSE_EXITED, event->AsMouseEvent()->type());
}
TEST_F(PenProcessorTest, TypicalCaseDMEnabled) {
ui::SequentialIDGenerator id_generator(0);
PenEventProcessor processor(&id_generator,
/*direct_manipulation_enabled*/ true);
POINTER_PEN_INFO pen_info;
memset(&pen_info, 0, sizeof(POINTER_PEN_INFO));
gfx::Point point(100, 100);
// Set up the modifier state that shift is down so we can test
// modifiers are propagated for mouse and touch events.
BYTE restore_key_state[256];
GetKeyboardState(restore_key_state);
BYTE shift_key_state[256];
memset(shift_key_state, 0, sizeof(shift_key_state));
// Mask high order bit on indicating it is down.
// See MSDN GetKeyState().
shift_key_state[VK_SHIFT] |= 0x80;
SetKeyboardState(shift_key_state);
std::unique_ptr<ui::Event> event =
processor.GenerateEvent(WM_POINTERENTER, 0, pen_info, point);
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsMouseEvent());
EXPECT_EQ(ui::ET_MOUSE_ENTERED, event->AsMouseEvent()->type());
EXPECT_TRUE(event->flags() & ui::EF_SHIFT_DOWN);
pen_info.pointerInfo.pointerFlags =
POINTER_FLAG_INCONTACT | POINTER_FLAG_FIRSTBUTTON;
pen_info.pointerInfo.ButtonChangeType = POINTER_CHANGE_FIRSTBUTTON_DOWN;
event = processor.GenerateEvent(WM_POINTERDOWN, 0, pen_info, point);
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsTouchEvent());
EXPECT_EQ(ui::ET_TOUCH_PRESSED, event->AsTouchEvent()->type());
EXPECT_TRUE(event->flags() & ui::EF_SHIFT_DOWN);
// Restore the keyboard state back to what it was in the beginning.
SetKeyboardState(restore_key_state);
pen_info.pointerInfo.ButtonChangeType = POINTER_CHANGE_NONE;
event = processor.GenerateEvent(WM_POINTERUPDATE, 0, pen_info, point);
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsTouchEvent());
EXPECT_EQ(ui::ET_TOUCH_MOVED, event->AsTouchEvent()->type());
pen_info.pointerInfo.pointerFlags = POINTER_FLAG_NONE;
pen_info.pointerInfo.ButtonChangeType = POINTER_CHANGE_FIRSTBUTTON_UP;
event = processor.GenerateEvent(WM_POINTERUP, 0, pen_info, point);
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsTouchEvent());
EXPECT_EQ(ui::ET_TOUCH_RELEASED, event->AsTouchEvent()->type());
pen_info.pointerInfo.ButtonChangeType = POINTER_CHANGE_NONE;
event = processor.GenerateEvent(WM_POINTERUPDATE, 0, pen_info, point);
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsMouseEvent());
EXPECT_EQ(ui::ET_MOUSE_MOVED, event->type());
event = processor.GenerateEvent(WM_POINTERLEAVE, 0, pen_info, point);
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsMouseEvent());
EXPECT_EQ(ui::ET_MOUSE_EXITED, event->AsMouseEvent()->type());
}
TEST_F(PenProcessorTest, UnpairedPointerDownTouchDMEnabled) {
ui::SequentialIDGenerator id_generator(0);
PenEventProcessor processor(&id_generator,
/*direct_manipulation_enabled*/ true);
POINTER_PEN_INFO pen_info;
memset(&pen_info, 0, sizeof(POINTER_PEN_INFO));
gfx::Point point(100, 100);
pen_info.pointerInfo.pointerFlags =
POINTER_FLAG_INCONTACT | POINTER_FLAG_FIRSTBUTTON;
pen_info.pointerInfo.ButtonChangeType = POINTER_CHANGE_FIRSTBUTTON_UP;
std::unique_ptr<ui::Event> event =
processor.GenerateEvent(WM_POINTERUP, 0, pen_info, point);
EXPECT_EQ(nullptr, event.get());
}
TEST_F(PenProcessorTest, UnpairedPointerDownMouseDMEnabled) {
ui::SequentialIDGenerator id_generator(0);
PenEventProcessor processor(&id_generator,
/*direct_manipulation_enabled*/ true);
POINTER_PEN_INFO pen_info;
memset(&pen_info, 0, sizeof(POINTER_PEN_INFO));
gfx::Point point(100, 100);
pen_info.pointerInfo.pointerFlags = POINTER_FLAG_FIRSTBUTTON;
pen_info.pointerInfo.ButtonChangeType = POINTER_CHANGE_FIRSTBUTTON_UP;
std::unique_ptr<ui::Event> event =
processor.GenerateEvent(WM_POINTERUP, 0, pen_info, point);
EXPECT_EQ(nullptr, event.get());
}
TEST_F(PenProcessorTest, TouchFlagDMEnabled) {
ui::SequentialIDGenerator id_generator(0);
PenEventProcessor processor(&id_generator,
/*direct_manipulation_enabled*/ true);
POINTER_PEN_INFO pen_info;
memset(&pen_info, 0, sizeof(POINTER_PEN_INFO));
gfx::Point point(100, 100);
pen_info.pointerInfo.pointerFlags =
POINTER_FLAG_INCONTACT | POINTER_FLAG_FIRSTBUTTON;
pen_info.pointerInfo.ButtonChangeType = POINTER_CHANGE_FIRSTBUTTON_DOWN;
std::unique_ptr<ui::Event> event =
processor.GenerateEvent(WM_POINTERDOWN, 0, pen_info, point);
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsTouchEvent());
EXPECT_EQ(ui::ET_TOUCH_PRESSED, event->AsTouchEvent()->type());
EXPECT_TRUE(event->flags() & ui::EF_LEFT_MOUSE_BUTTON);
pen_info.pointerInfo.pointerFlags = POINTER_FLAG_UP;
pen_info.pointerInfo.ButtonChangeType = POINTER_CHANGE_FIRSTBUTTON_UP;
event = processor.GenerateEvent(WM_POINTERUP, 0, pen_info, point);
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsTouchEvent());
EXPECT_EQ(ui::ET_TOUCH_RELEASED, event->AsTouchEvent()->type());
EXPECT_FALSE(event->flags() & ui::EF_LEFT_MOUSE_BUTTON);
}
TEST_F(PenProcessorTest, MouseFlagDMEnabled) {
ui::SequentialIDGenerator id_generator(0);
PenEventProcessor processor(&id_generator,
/*direct_manipulation_enabled*/ true);
POINTER_PEN_INFO pen_info;
memset(&pen_info, 0, sizeof(POINTER_PEN_INFO));
gfx::Point point(100, 100);
pen_info.pointerInfo.pointerFlags = POINTER_FLAG_FIRSTBUTTON;
pen_info.pointerInfo.ButtonChangeType = POINTER_CHANGE_FIRSTBUTTON_DOWN;
std::unique_ptr<ui::Event> event =
processor.GenerateEvent(WM_POINTERDOWN, 0, pen_info, point);
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsMouseEvent());
EXPECT_EQ(ui::ET_MOUSE_PRESSED, event->AsMouseEvent()->type());
EXPECT_TRUE(event->flags() & ui::EF_LEFT_MOUSE_BUTTON);
EXPECT_EQ(ui::EF_LEFT_MOUSE_BUTTON,
event->AsMouseEvent()->changed_button_flags());
pen_info.pointerInfo.pointerFlags = POINTER_FLAG_NONE;
pen_info.pointerInfo.ButtonChangeType = POINTER_CHANGE_FIRSTBUTTON_UP;
event = processor.GenerateEvent(WM_POINTERUP, 0, pen_info, point);
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsMouseEvent());
EXPECT_EQ(ui::ET_MOUSE_RELEASED, event->AsMouseEvent()->type());
EXPECT_TRUE(event->flags() & ui::EF_LEFT_MOUSE_BUTTON);
EXPECT_EQ(ui::EF_LEFT_MOUSE_BUTTON,
event->AsMouseEvent()->changed_button_flags());
}
TEST_F(PenProcessorTest, PenEraserFlagDMEnabled) {
ui::SequentialIDGenerator id_generator(0);
PenEventProcessor processor(&id_generator,
/*direct_manipulation_enabled*/ true);
POINTER_PEN_INFO pen_info;
memset(&pen_info, 0, sizeof(POINTER_PEN_INFO));
gfx::Point point(100, 100);
pen_info.pointerInfo.pointerFlags =
POINTER_FLAG_INCONTACT | POINTER_FLAG_FIRSTBUTTON;
pen_info.pointerInfo.ButtonChangeType = POINTER_CHANGE_FIRSTBUTTON_DOWN;
pen_info.penFlags = PEN_FLAG_ERASER;
std::unique_ptr<ui::Event> event =
processor.GenerateEvent(WM_POINTERDOWN, 0, pen_info, point);
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsTouchEvent());
EXPECT_EQ(ui::ET_TOUCH_PRESSED, event->AsTouchEvent()->type());
EXPECT_EQ(ui::EventPointerType::kEraser,
event->AsTouchEvent()->pointer_details().pointer_type);
pen_info.pointerInfo.pointerFlags = POINTER_FLAG_UP;
pen_info.pointerInfo.ButtonChangeType = POINTER_CHANGE_FIRSTBUTTON_UP;
event = processor.GenerateEvent(WM_POINTERUP, 0, pen_info, point);
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsTouchEvent());
EXPECT_EQ(ui::ET_TOUCH_RELEASED, event->AsTouchEvent()->type());
EXPECT_EQ(ui::EventPointerType::kEraser,
event->AsTouchEvent()->pointer_details().pointer_type);
}
TEST_F(PenProcessorTest, MultiPenDMEnabled) {
ui::SequentialIDGenerator id_generator(0);
PenEventProcessor processor(&id_generator,
/*direct_manipulation_enabled*/ true);
const int kPenCount = 3;
POINTER_PEN_INFO pen_info[kPenCount];
for (auto& i : pen_info) {
memset(&i, 0, sizeof(POINTER_PEN_INFO));
}
gfx::Point point(100, 100);
for (int i = 0; i < kPenCount; i++) {
pen_info[i].pointerInfo.pointerFlags =
POINTER_FLAG_INCONTACT | POINTER_FLAG_FIRSTBUTTON;
pen_info[i].pointerInfo.ButtonChangeType = POINTER_CHANGE_FIRSTBUTTON_DOWN;
int pointer_id = i;
std::unique_ptr<ui::Event> event =
processor.GenerateEvent(WM_POINTERDOWN, pointer_id, pen_info[i], point);
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsTouchEvent());
EXPECT_EQ(ui::ET_TOUCH_PRESSED, event->AsTouchEvent()->type());
}
for (int i = 0; i < kPenCount; i++) {
pen_info[i].pointerInfo.pointerFlags = POINTER_FLAG_UP;
pen_info[i].pointerInfo.ButtonChangeType = POINTER_CHANGE_FIRSTBUTTON_UP;
int pointer_id = i;
std::unique_ptr<ui::Event> event =
processor.GenerateEvent(WM_POINTERUP, pointer_id, pen_info[i], point);
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsTouchEvent());
EXPECT_EQ(ui::ET_TOUCH_RELEASED, event->AsTouchEvent()->type());
}
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/win/pen_event_processor_unittest.cc | C++ | unknown | 11,954 |
// 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/win/pen_id_handler.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/com_init_util.h"
#include "base/win/core_winrt_util.h"
#include "base/win/hstring_reference.h"
#include "base/win/win_util.h"
#include "base/win/windows_version.h"
namespace views {
namespace {
bool PenDeviceApiSupported() {
// PenDevice API only works properly on WIN11 or Win10 post v19044.
return base::win::GetVersion() > base::win::Version::WIN10_21H2 ||
(base::win::GetVersion() == base::win::Version::WIN10_21H2 &&
base::win::OSInfo::GetInstance()->version_number().patch >= 1503);
}
} // namespace
using ABI::Windows::Devices::Input::IPenDevice;
using ABI::Windows::UI::Input::IPointerPoint;
using ABI::Windows::UI::Input::IPointerPointProperties;
using Microsoft::WRL::ComPtr;
#define HID_USAGE_PAGE_DIGITIZER ((UINT)0x0d)
#define HID_USAGE_ID_TSN ((UINT)0x5b)
#define HID_USAGE_ID_TVID ((UINT)0x91)
PenIdHandler::GetPenDeviceStatics get_pen_device_statics = nullptr;
PenIdHandler::GetPointerPointStatics get_pointer_point_statics = nullptr;
PenIdHandler::ScopedPenIdStaticsForTesting::ScopedPenIdStaticsForTesting(
PenIdHandler::GetPenDeviceStatics pen_device_statics,
PenIdHandler::GetPointerPointStatics pointer_point_statics)
: pen_device_resetter_(&get_pen_device_statics, pen_device_statics),
pointer_point_resetter_(&get_pointer_point_statics,
pointer_point_statics) {}
PenIdHandler::ScopedPenIdStaticsForTesting::~ScopedPenIdStaticsForTesting() =
default;
PenIdHandler::PenIdHandler() {
base::win::AssertComInitialized();
HRESULT hr = base::win::RoGetActivationFactory(
base::win::HStringReference(RuntimeClass_Windows_Devices_Input_PenDevice)
.Get(),
IID_PPV_ARGS(&pen_device_statics_));
if (FAILED(hr)) {
pen_device_statics_ = nullptr;
}
hr = base::win::RoGetActivationFactory(
base::win::HStringReference(RuntimeClass_Windows_UI_Input_PointerPoint)
.Get(),
IID_PPV_ARGS(&pointer_point_statics_));
if (FAILED(hr)) {
pointer_point_statics_ = nullptr;
}
}
PenIdHandler::~PenIdHandler() = default;
absl::optional<int32_t> PenIdHandler::TryGetPenUniqueId(UINT32 pointer_id) {
if (!PenDeviceApiSupported()) {
return absl::nullopt;
}
absl::optional<std::string> guid = TryGetGuid(pointer_id);
if (guid.has_value()) {
auto entry = guid_to_id_map_.insert({guid.value(), current_id_});
if (entry.second) {
current_id_++;
}
return entry.first->second;
}
PenIdHandler::TransducerId transducer_id = TryGetTransducerId(pointer_id);
if (transducer_id.tsn != TransducerId::kInvalidTSN) {
if (!transducer_id_to_id_map_.contains(transducer_id)) {
transducer_id_to_id_map_[transducer_id] = current_id_++;
}
return transducer_id_to_id_map_[transducer_id];
}
return absl::nullopt;
}
absl::optional<std::string> PenIdHandler::TryGetGuid(UINT32 pointer_id) const {
// Override pen device statics if in a test.
const Microsoft::WRL::ComPtr<ABI::Windows::Devices::Input::IPenDeviceStatics>
pen_device_statics = get_pen_device_statics ? (*get_pen_device_statics)()
: pen_device_statics_;
if (!pen_device_statics) {
return absl::nullopt;
}
Microsoft::WRL::ComPtr<ABI::Windows::Devices::Input::IPenDevice> pen_device;
HRESULT hr = pen_device_statics->GetFromPointerId(pointer_id, &pen_device);
// `pen_device` is null if the pen does not support a unique ID.
if (FAILED(hr) || !pen_device) {
return absl::nullopt;
}
GUID pen_device_guid;
hr = pen_device->get_PenId(&pen_device_guid);
if (FAILED(hr)) {
return absl::nullopt;
}
return base::WideToUTF8(base::win::WStringFromGUID(pen_device_guid));
}
PenIdHandler::TransducerId PenIdHandler::TryGetTransducerId(
UINT32 pointer_id) const {
TransducerId transducer_id;
// Override pointer point statics if in a test.
const Microsoft::WRL::ComPtr<ABI::Windows::UI::Input::IPointerPointStatics>
pointer_point_statics =
get_pointer_point_statics ? (*get_pointer_point_statics)()
: pointer_point_statics_;
if (!pointer_point_statics) {
return transducer_id;
}
ComPtr<IPointerPoint> pointer_point;
HRESULT hr =
pointer_point_statics->GetCurrentPoint(pointer_id, &pointer_point);
if (hr != S_OK) {
return transducer_id;
}
ComPtr<IPointerPointProperties> pointer_point_properties;
hr = pointer_point->get_Properties(&pointer_point_properties);
if (hr != S_OK) {
return transducer_id;
}
// Retrieve Transducer Serial Number and check if it's valid.
boolean has_tsn = false;
hr = pointer_point_properties->HasUsage(HID_USAGE_PAGE_DIGITIZER,
HID_USAGE_ID_TSN, &has_tsn);
if (hr != S_OK || !has_tsn) {
return transducer_id;
}
hr = pointer_point_properties->GetUsageValue(
HID_USAGE_PAGE_DIGITIZER, HID_USAGE_ID_TSN, &transducer_id.tsn);
if (hr != S_OK || transducer_id.tsn == TransducerId::kInvalidTSN) {
return transducer_id;
}
// Retrieve Transducer Vendor Id and check if it's valid.
boolean has_tvid = false;
hr = pointer_point_properties->HasUsage(HID_USAGE_PAGE_DIGITIZER,
HID_USAGE_ID_TVID, &has_tvid);
if (hr != S_OK || !has_tvid) {
return transducer_id;
}
hr = pointer_point_properties->GetUsageValue(
HID_USAGE_PAGE_DIGITIZER, HID_USAGE_ID_TVID, &transducer_id.tvid);
return transducer_id;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/win/pen_id_handler.cc | C++ | unknown | 5,776 |
// 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_WIN_PEN_ID_HANDLER_H_
#define UI_VIEWS_WIN_PEN_ID_HANDLER_H_
#include <combaseapi.h>
#include <stdint.h>
#include <windows.devices.input.h>
#include <windows.ui.input.h>
#include <wrl.h>
#include <string>
#include "base/auto_reset.h"
#include "base/containers/flat_map.h"
#include "base/gtest_prod_util.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/views/views_export.h"
namespace views {
// This class is responsible for retrieving the unique pen id from Windows,
// and mapping it to a unique id that will be used by Blink. When the unique
// id is fetched, the device's GUID is queried first. If unavailable, then
// the transducer id - which includes the transducer serial number and vendor
// id - is retrieved. These IDs are then mapped to a separate unique value,
// which is ultimately returned.
class VIEWS_EXPORT PenIdHandler {
public:
using GetPenDeviceStatics = Microsoft::WRL::ComPtr<
ABI::Windows::Devices::Input::IPenDeviceStatics> (*)();
using GetPointerPointStatics = Microsoft::WRL::ComPtr<
ABI::Windows::UI::Input::IPointerPointStatics> (*)();
class VIEWS_EXPORT [[maybe_unused, nodiscard]] ScopedPenIdStaticsForTesting {
public:
explicit ScopedPenIdStaticsForTesting(
GetPenDeviceStatics pen_device_statics,
GetPointerPointStatics pointer_point_statics);
~ScopedPenIdStaticsForTesting();
private:
base::AutoReset<GetPenDeviceStatics> pen_device_resetter_;
base::AutoReset<GetPointerPointStatics> pointer_point_resetter_;
};
PenIdHandler();
virtual ~PenIdHandler();
absl::optional<int32_t> TryGetPenUniqueId(UINT32 pointer_id);
private:
friend class FakePenIdHandler;
friend class FakePenIdHandlerFakeStatics;
FRIEND_TEST_ALL_PREFIXES(PenIdHandlerTest, GetGuidMapping);
FRIEND_TEST_ALL_PREFIXES(PenIdHandlerTest, PenDeviceStaticsFailedToSet);
FRIEND_TEST_ALL_PREFIXES(PenIdHandlerTest, TryGetGuidHandlesBadStatics);
FRIEND_TEST_ALL_PREFIXES(PenIdHandlerTest, PenDeviceStaticsFailedToSet);
FRIEND_TEST_ALL_PREFIXES(PenIdHandlerTest, TryGetTransducerIdHandlesErrors);
struct TransducerId {
int32_t tsn = 0;
int32_t tvid = 0;
static constexpr int32_t kInvalidTSN = 0;
bool operator<(const TransducerId& other) const {
if (this->tsn != other.tsn) {
return this->tsn < other.tsn;
}
return this->tvid < other.tvid;
}
bool operator==(const TransducerId& other) const {
if (this->tsn == other.tsn && this->tvid == other.tvid) {
return true;
}
return false;
}
};
// Virtual for unit testing.
// Checks if a PenDevice can be retrieved for the `pointer_id` and returns its
// GUID if it exists.
virtual absl::optional<std::string> TryGetGuid(UINT32 pointer_id) const;
// This is a fallback scenario when TryGetGUID doesn't retrieve a PenDevice.
// Happens when the device doesn't have both TSN/TVID (e.g.
// SurfaceHub 1 + SurfaceHub Pen -> only has TSN, no TVID).
virtual TransducerId TryGetTransducerId(UINT32 pointer_id) const;
base::flat_map<std::string, int32_t> guid_to_id_map_;
// Mapping from "Transducer Serial Number (TSN)" to `unique_id`. More
// information on TSN: https://www.usb.org/sites/default/files/hut1_22.pdf
base::flat_map<TransducerId, int32_t> transducer_id_to_id_map_;
int32_t current_id_ = 0;
Microsoft::WRL::ComPtr<ABI::Windows::Devices::Input::IPenDeviceStatics>
pen_device_statics_;
Microsoft::WRL::ComPtr<ABI::Windows::UI::Input::IPointerPointStatics>
pointer_point_statics_;
};
} // namespace views
#endif // UI_VIEWS_WIN_PEN_ID_HANDLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/win/pen_id_handler.h | C++ | unknown | 3,787 |
// 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/win/pen_id_handler.h"
#include "base/win/scoped_winrt_initializer.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/views/win/test_support/fake_ipen_device.h"
#include "ui/views/win/test_support/fake_ipen_device_statics.h"
#include "ui/views/win/test_support/fake_ipen_pointer_point_statics.h"
#include "ui/views/win/test_support/fake_ipointer_point.h"
#include "ui/views/win/test_support/fake_ipointer_point_properties.h"
namespace views {
using ABI::Windows::Devices::Input::IPenDeviceStatics;
using ABI::Windows::UI::Input::IPointerPointStatics;
constexpr int kPenId0 = 0;
constexpr int kPenId1 = 1;
constexpr int kPenId2 = 2;
constexpr int kPointerId1 = 1111;
constexpr int kPointerId2 = 2222;
constexpr int kPointerId3 = 3333;
constexpr int kPointerId4 = 4444;
constexpr int kPointerId5 = 5555;
class FakePenIdHandler : public PenIdHandler {
public:
FakePenIdHandler(
Microsoft::WRL::ComPtr<IPenDeviceStatics> pen_device_statics,
Microsoft::WRL::ComPtr<IPointerPointStatics> pointer_point_statics) {
pen_device_statics_ = pen_device_statics;
pointer_point_statics_ = pointer_point_statics;
}
};
class PenIdHandlerTest : public ::testing::Test {
public:
PenIdHandlerTest() = default;
~PenIdHandlerTest() override = default;
// testing::Test overrides.
void SetUp() override;
void TearDown() override;
private:
base::win::ScopedWinrtInitializer scoped_winrt_initializer_;
};
void PenIdHandlerTest::SetUp() {
ASSERT_TRUE(scoped_winrt_initializer_.Succeeded());
}
void PenIdHandlerTest::TearDown() {
FakeIPenDeviceStatics::GetInstance()->SimulateAllPenDevicesRemoved();
FakeIPenPointerPointStatics::GetInstance()->ClearPointerPointsMap();
}
// Tests TryGetPenUniqueId for devices that have a guid. The unique guid should
// be correctly maped to a unique pen id, which is the value that is returned
// by TryGetPenUniqueId.
TEST_F(PenIdHandlerTest, GetGuidMapping) {
Microsoft::WRL::ComPtr<FakeIPenDeviceStatics> pen_device_statics =
FakeIPenDeviceStatics::GetInstance();
FakePenIdHandler pen_id_handler(pen_device_statics, nullptr);
// Make sure Get GUID works correctly.
const auto fake_pen_device_1 = Microsoft::WRL::Make<FakeIPenDevice>();
const auto fake_pen_device_2 = Microsoft::WRL::Make<FakeIPenDevice>();
const auto fake_pen_device_3 = Microsoft::WRL::Make<FakeIPenDevice>();
pen_device_statics->SimulatePenEventGenerated(kPointerId1, fake_pen_device_1);
pen_device_statics->SimulatePenEventGenerated(kPointerId2, fake_pen_device_2);
pen_device_statics->SimulatePenEventGenerated(kPointerId3, fake_pen_device_3);
pen_device_statics->SimulatePenEventGenerated(kPointerId4, fake_pen_device_1);
const absl::optional<int32_t> id =
pen_id_handler.TryGetPenUniqueId(kPointerId1);
const absl::optional<int32_t> id2 =
pen_id_handler.TryGetPenUniqueId(kPointerId2);
EXPECT_NE(id, id2);
const absl::optional<int32_t> id3 =
pen_id_handler.TryGetPenUniqueId(kPointerId3);
EXPECT_NE(id2, id3);
EXPECT_NE(id, id3);
// Different pointer id generated from a previously seen device should return
// that device's unique id.
EXPECT_EQ(id, pen_id_handler.TryGetPenUniqueId(kPointerId4));
}
// Tests TryGetPenUniqueId for devices that don't have a guid, but do have
// a transducer id. Makes sure the correct TransducerId is returned given a
// pointer id.
TEST_F(PenIdHandlerTest, GetTransducerIdMapping) {
Microsoft::WRL::ComPtr<FakeIPenPointerPointStatics> pointer_point_statics =
FakeIPenPointerPointStatics::GetInstance();
FakePenIdHandler pen_id_handler(nullptr, pointer_point_statics);
// Make sure Get GUID works correctly.
const auto p1 = Microsoft::WRL::Make<FakeIPointerPoint>(
/*getProperties throw error*/ false,
/*has usage error*/ false,
/*get usage error*/ false,
/*tsn*/ 100,
/*tvid*/ 1);
const auto p2 = Microsoft::WRL::Make<FakeIPointerPoint>(
/*getProperties throw error*/ false,
/*has usage error*/ false,
/*get usage error*/ false,
/*tsn*/ 200,
/*tvid*/ 1);
const auto p3 = Microsoft::WRL::Make<FakeIPointerPoint>(
/*getProperties throw error*/ false,
/*has usage error*/ false,
/*get usage error*/ false,
/*tsn*/ 100,
/*tvid*/ 2);
const auto p4 = Microsoft::WRL::Make<FakeIPointerPoint>(
/*getProperties throw error*/ false,
/*has usage error*/ false,
/*get usage error*/ false,
/*tsn*/ 100,
/*tvid*/ 1);
pointer_point_statics->AddPointerPoint(kPointerId1, p1);
pointer_point_statics->AddPointerPoint(kPointerId2, p2);
pointer_point_statics->AddPointerPoint(kPointerId3, p3);
pointer_point_statics->AddPointerPoint(kPointerId4, p4);
absl::optional<int32_t> id = pen_id_handler.TryGetPenUniqueId(kPointerId1);
EXPECT_EQ(id, kPenId0);
// Different serial number to previous should return a new unique id.
id = pen_id_handler.TryGetPenUniqueId(kPointerId2);
EXPECT_EQ(id, kPenId1);
// Same serial number but different vendor id should result in a different
// returned unique id.
id = pen_id_handler.TryGetPenUniqueId(kPointerId3);
EXPECT_EQ(id, kPenId2);
// Persisted id should be returned if transducer id is recognized.
id = pen_id_handler.TryGetPenUniqueId(kPointerId4);
EXPECT_EQ(id, kPenId0);
// Unrecognized id should return a null optional.
id = pen_id_handler.TryGetPenUniqueId(kPointerId5);
EXPECT_EQ(id, absl::nullopt);
}
// Simulate statics not being set. This should result in TryGetGuid returning
// absl::nullopt and TryGetTransducerId returning an invalid Transducer ID.
// Ultimately TryGetPenUniqueId should return null.
TEST_F(PenIdHandlerTest, PenDeviceStaticsFailedToSet) {
FakePenIdHandler pen_id_handler(nullptr, nullptr);
EXPECT_EQ(pen_id_handler.TryGetGuid(kPointerId1), absl::nullopt);
EXPECT_EQ(pen_id_handler.TryGetTransducerId(kPointerId1),
PenIdHandler::TransducerId());
EXPECT_EQ(pen_id_handler.TryGetPenUniqueId(kPointerId1), absl::nullopt);
}
TEST_F(PenIdHandlerTest, TryGetGuidHandlesBadStatics) {
// Make sure `TryGetGUID` fails when there is no ID.
Microsoft::WRL::ComPtr<FakeIPenDeviceStatics> pen_device_statics =
FakeIPenDeviceStatics::GetInstance();
FakePenIdHandler pen_id_handler(pen_device_statics, nullptr);
EXPECT_EQ(pen_id_handler.TryGetGuid(kPointerId1), absl::nullopt);
// When there is a GUID, it should be plumbed.
const auto fake_pen_device = Microsoft::WRL::Make<FakeIPenDevice>();
pen_device_statics->SimulatePenEventGenerated(kPointerId1, fake_pen_device);
EXPECT_EQ(pen_id_handler.TryGetGuid(kPointerId1), fake_pen_device->GetGuid());
}
TEST_F(PenIdHandlerTest, TryGetTransducerIdHandlesErrors) {
Microsoft::WRL::ComPtr<FakeIPenPointerPointStatics> pointer_point_statics =
FakeIPenPointerPointStatics::GetInstance();
FakePenIdHandler pen_id_handler(nullptr, pointer_point_statics);
// No current point found.
EXPECT_EQ(pen_id_handler.TryGetTransducerId(kPointerId1),
PenIdHandler::TransducerId());
// Current point found but point->GetProperties throws error.
const auto p = Microsoft::WRL::Make<FakeIPointerPoint>(
/*getProperties throw error*/ true);
pointer_point_statics->AddPointerPoint(kPointerId1, p);
EXPECT_EQ(pen_id_handler.TryGetTransducerId(kPointerId1),
PenIdHandler::TransducerId());
// has usage throws error.
const auto p1 = Microsoft::WRL::Make<FakeIPointerPoint>(
/*getProperties throw error*/ false,
/*has usage error*/ true);
pointer_point_statics->AddPointerPoint(kPointerId2, p1);
EXPECT_EQ(pen_id_handler.TryGetTransducerId(kPointerId2),
PenIdHandler::TransducerId());
// get usage throws error.
const auto p2 = Microsoft::WRL::Make<FakeIPointerPoint>(
/*getProperties throw error*/ false,
/*has usage error*/ false,
/*get usage error*/ true);
pointer_point_statics->AddPointerPoint(kPointerId3, p2);
EXPECT_EQ(pen_id_handler.TryGetTransducerId(kPointerId3),
PenIdHandler::TransducerId());
// Entire pipeline works correctly.
const auto p3 = Microsoft::WRL::Make<FakeIPointerPoint>(
/*getProperties throw error*/ false,
/*has usage error*/ false,
/*get usage error*/ false,
/*tsn*/ 100,
/*tvid*/ 200);
pointer_point_statics->AddPointerPoint(kPointerId4, p3);
EXPECT_EQ(pen_id_handler.TryGetTransducerId(kPointerId4),
(PenIdHandler::TransducerId{/*tsn*/ 100, /*tvid*/ 200}));
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/win/pen_id_handler_unittest.cc | C++ | unknown | 8,755 |
// 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/win/scoped_enable_unadjusted_mouse_events_win.h"
#include "base/logging.h"
#include "ui/views/win/hwnd_message_handler.h"
namespace views {
namespace {
// From the HID Usage Tables specification.
constexpr USHORT kGenericDesktopPage = 1;
constexpr USHORT kMouseUsage = 2;
std::unique_ptr<RAWINPUTDEVICE> GetRawInputDevices(HWND hwnd, DWORD flags) {
std::unique_ptr<RAWINPUTDEVICE> device = std::make_unique<RAWINPUTDEVICE>();
device->dwFlags = flags;
device->usUsagePage = kGenericDesktopPage;
device->usUsage = kMouseUsage;
device->hwndTarget = hwnd;
return device;
}
} // namespace
ScopedEnableUnadjustedMouseEventsWin::ScopedEnableUnadjustedMouseEventsWin(
HWNDMessageHandler* owner)
: owner_(owner) {}
ScopedEnableUnadjustedMouseEventsWin::~ScopedEnableUnadjustedMouseEventsWin() {
// Stop receiving raw input.
std::unique_ptr<RAWINPUTDEVICE> device(
GetRawInputDevices(nullptr, RIDEV_REMOVE));
if (!RegisterRawInputDevices(device.get(), 1, sizeof(*device)))
PLOG(INFO) << "RegisterRawInputDevices() failed for RIDEV_REMOVE ";
DCHECK(owner_->using_wm_input());
owner_->set_using_wm_input(false);
}
// static
std::unique_ptr<ScopedEnableUnadjustedMouseEventsWin>
ScopedEnableUnadjustedMouseEventsWin::StartMonitor(HWNDMessageHandler* owner) {
std::unique_ptr<RAWINPUTDEVICE> device(
GetRawInputDevices(owner->hwnd(), RIDEV_INPUTSINK));
if (!RegisterRawInputDevices(device.get(), 1, sizeof(*device))) {
PLOG(INFO) << "RegisterRawInputDevices() failed for RIDEV_INPUTSINK ";
return nullptr;
}
DCHECK(!owner->using_wm_input());
owner->set_using_wm_input(true);
return std::make_unique<ScopedEnableUnadjustedMouseEventsWin>(owner);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/win/scoped_enable_unadjusted_mouse_events_win.cc | C++ | unknown | 1,895 |
// 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_WIN_SCOPED_ENABLE_UNADJUSTED_MOUSE_EVENTS_WIN_H_
#define UI_VIEWS_WIN_SCOPED_ENABLE_UNADJUSTED_MOUSE_EVENTS_WIN_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "ui/aura/scoped_enable_unadjusted_mouse_events.h"
namespace views {
class HWNDMessageHandler;
// This class handles register and unregister unadjusted mouse events on
// windows. Destroying an instance of this class will unregister unadjusted
// mouse events and stops handling mouse WM_INPUT messages.
class ScopedEnableUnadjustedMouseEventsWin
: public aura::ScopedEnableUnadjustedMouseEvents {
public:
explicit ScopedEnableUnadjustedMouseEventsWin(HWNDMessageHandler* owner);
ScopedEnableUnadjustedMouseEventsWin(
const ScopedEnableUnadjustedMouseEventsWin&) = delete;
ScopedEnableUnadjustedMouseEventsWin& operator=(
const ScopedEnableUnadjustedMouseEventsWin&) = delete;
~ScopedEnableUnadjustedMouseEventsWin() override;
// Register to receive raw mouse input. If success, creates a new
// ScopedEnableUnadjustedMouseEventsWin instance.
static std::unique_ptr<ScopedEnableUnadjustedMouseEventsWin> StartMonitor(
HWNDMessageHandler* owner);
raw_ptr<HWNDMessageHandler> owner_;
};
} // namespace views
#endif // UI_VIEWS_WIN_SCOPED_ENABLE_UNADJUSTED_MOUSE_EVENTS_WIN_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/win/scoped_enable_unadjusted_mouse_events_win.h | C++ | unknown | 1,460 |
// 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/win/scoped_fullscreen_visibility.h"
#include <utility>
#include "base/check.h"
namespace views {
// static
std::map<HWND, int>* ScopedFullscreenVisibility::full_screen_windows_ = nullptr;
ScopedFullscreenVisibility::ScopedFullscreenVisibility(HWND hwnd)
: hwnd_(hwnd) {
if (!full_screen_windows_)
full_screen_windows_ = new FullscreenHWNDs;
FullscreenHWNDs::iterator it = full_screen_windows_->find(hwnd_);
if (it != full_screen_windows_->end()) {
it->second++;
} else {
full_screen_windows_->insert(std::make_pair(hwnd_, 1));
// NOTE: Be careful not to activate any windows here (for example, calling
// ShowWindow(SW_HIDE) will automatically activate another window). This
// code can be called while a window is being deactivated, and activating
// another window will screw up the activation that is already in progress.
SetWindowPos(hwnd_, nullptr, 0, 0, 0, 0,
SWP_HIDEWINDOW | SWP_NOACTIVATE | SWP_NOMOVE |
SWP_NOREPOSITION | SWP_NOSIZE | SWP_NOZORDER);
}
}
ScopedFullscreenVisibility::~ScopedFullscreenVisibility() {
FullscreenHWNDs::iterator it = full_screen_windows_->find(hwnd_);
DCHECK(it != full_screen_windows_->end());
if (--it->second == 0) {
full_screen_windows_->erase(it);
ShowWindow(hwnd_, SW_SHOW);
}
if (full_screen_windows_->empty()) {
delete full_screen_windows_;
full_screen_windows_ = nullptr;
}
}
// static
bool ScopedFullscreenVisibility::IsHiddenForFullscreen(HWND hwnd) {
if (!full_screen_windows_)
return false;
return full_screen_windows_->find(hwnd) != full_screen_windows_->end();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/win/scoped_fullscreen_visibility.cc | C++ | unknown | 1,830 |
// 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_WIN_SCOPED_FULLSCREEN_VISIBILITY_H_
#define UI_VIEWS_WIN_SCOPED_FULLSCREEN_VISIBILITY_H_
#include <windows.h>
#include <map>
#include "ui/views/views_export.h"
namespace views {
// Scoping class that ensures a HWND remains hidden while it enters or leaves
// the fullscreen state. This reduces some flicker-jank that an application UI
// might suffer.
class VIEWS_EXPORT ScopedFullscreenVisibility {
public:
explicit ScopedFullscreenVisibility(HWND hwnd);
ScopedFullscreenVisibility(const ScopedFullscreenVisibility&) = delete;
ScopedFullscreenVisibility& operator=(const ScopedFullscreenVisibility&) =
delete;
~ScopedFullscreenVisibility();
// Returns true if |hwnd| is currently hidden due to instance(s) of this
// class.
static bool IsHiddenForFullscreen(HWND hwnd);
private:
using FullscreenHWNDs = std::map<HWND, int>;
HWND hwnd_;
static FullscreenHWNDs* full_screen_windows_;
};
} // namespace views
#endif // UI_VIEWS_WIN_SCOPED_FULLSCREEN_VISIBILITY_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/win/scoped_fullscreen_visibility.h | C++ | unknown | 1,166 |
// 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/win/test_support/fake_ipen_device.h"
#include <combaseapi.h>
#include <string>
#include "base/strings/utf_string_conversions.h"
#include "base/win/win_util.h"
namespace views {
FakeIPenDevice::FakeIPenDevice() {
// Initialize guid_ with a random GUID.
CHECK_EQ(CoCreateGuid(&guid_), S_OK);
}
FakeIPenDevice::~FakeIPenDevice() = default;
HRESULT FakeIPenDevice::get_PenId(GUID* value) {
*value = guid_;
return S_OK;
}
std::string FakeIPenDevice::GetGuid() const {
return base::WideToUTF8(base::win::WStringFromGUID(guid_));
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/win/test_support/fake_ipen_device.cc | C++ | unknown | 729 |
// 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_WIN_TEST_SUPPORT_FAKE_IPEN_DEVICE_H_
#define UI_VIEWS_WIN_TEST_SUPPORT_FAKE_IPEN_DEVICE_H_
#include <windows.devices.input.h>
#include <wrl.h>
#include <string>
namespace views {
class FakeIPenDevice final
: public Microsoft::WRL::RuntimeClass<
Microsoft::WRL::RuntimeClassFlags<
Microsoft::WRL::WinRt | Microsoft::WRL::InhibitRoOriginateError>,
ABI::Windows::Devices::Input::IPenDevice> {
public:
FakeIPenDevice();
FakeIPenDevice(const FakeIPenDevice&) = delete;
FakeIPenDevice& operator=(const FakeIPenDevice&) = delete;
~FakeIPenDevice() override;
// ABI::Windows::Devices::Input::IPenDevice:
IFACEMETHODIMP get_PenId(GUID* value) override;
// Helper method for getting the pen device GUID as a string.
std::string GetGuid() const;
private:
GUID guid_;
};
} // namespace views
#endif // UI_VIEWS_WIN_TEST_SUPPORT_FAKE_IPEN_DEVICE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/win/test_support/fake_ipen_device.h | C++ | unknown | 1,069 |
// 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/win/test_support/fake_ipen_device_statics.h"
#include "base/no_destructor.h"
using ABI::Windows::Devices::Input::IPenDevice;
namespace views {
FakeIPenDeviceStatics::FakeIPenDeviceStatics() = default;
FakeIPenDeviceStatics::~FakeIPenDeviceStatics() = default;
// static
FakeIPenDeviceStatics* FakeIPenDeviceStatics::GetInstance() {
static base::NoDestructor<FakeIPenDeviceStatics> instance;
return instance.get();
}
Microsoft::WRL::ComPtr<ABI::Windows::Devices::Input::IPenDeviceStatics>
FakeIPenDeviceStatics::FakeIPenDeviceStaticsComPtr() {
FakeIPenDeviceStatics* instance = GetInstance();
return static_cast<
Microsoft::WRL::ComPtr<ABI::Windows::Devices::Input::IPenDeviceStatics>>(
instance);
}
HRESULT FakeIPenDeviceStatics::GetFromPointerId(UINT32 pointer_id,
IPenDevice** result) {
auto pen_device = pen_device_map_.find(pointer_id);
if (pen_device == pen_device_map_.end()) {
return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
}
return pen_device->second.CopyTo(result);
}
void FakeIPenDeviceStatics::SimulatePenEventGenerated(
UINT32 pointer_id,
Microsoft::WRL::ComPtr<IPenDevice> pen_device) {
pen_device_map_[pointer_id] = pen_device;
}
void FakeIPenDeviceStatics::SimulateAllPenDevicesRemoved() {
pen_device_map_.clear();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/win/test_support/fake_ipen_device_statics.cc | C++ | unknown | 1,516 |
// 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_WIN_TEST_SUPPORT_FAKE_IPEN_DEVICE_STATICS_H_
#define UI_VIEWS_WIN_TEST_SUPPORT_FAKE_IPEN_DEVICE_STATICS_H_
#include <windows.devices.input.h>
#include <wrl.h>
#include <map>
namespace views {
class FakeIPenDeviceStatics final
: public Microsoft::WRL::RuntimeClass<
Microsoft::WRL::RuntimeClassFlags<
Microsoft::WRL::WinRt | Microsoft::WRL::InhibitRoOriginateError>,
ABI::Windows::Devices::Input::IPenDeviceStatics> {
public:
FakeIPenDeviceStatics();
FakeIPenDeviceStatics(const FakeIPenDeviceStatics&) = delete;
FakeIPenDeviceStatics& operator=(const FakeIPenDeviceStatics&) = delete;
~FakeIPenDeviceStatics() final;
static FakeIPenDeviceStatics* GetInstance();
static Microsoft::WRL::ComPtr<ABI::Windows::Devices::Input::IPenDeviceStatics>
FakeIPenDeviceStaticsComPtr();
// ABI::Windows::Devices::Input::IPenDeviceStatics:
IFACEMETHODIMP GetFromPointerId(
UINT32 pointer_id,
ABI::Windows::Devices::Input::IPenDevice** pen_device) override;
// Test methods
void SimulatePenEventGenerated(
UINT32 pointer_id,
Microsoft::WRL::ComPtr<ABI::Windows::Devices::Input::IPenDevice>
pen_device);
void SimulateAllPenDevicesRemoved();
private:
// Map pointer_id to pen device.
std::map<UINT32,
Microsoft::WRL::ComPtr<ABI::Windows::Devices::Input::IPenDevice>>
pen_device_map_;
};
} // namespace views
#endif // UI_VIEWS_WIN_TEST_SUPPORT_FAKE_IPEN_DEVICE_STATICS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/win/test_support/fake_ipen_device_statics.h | C++ | unknown | 1,648 |
// 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/win/test_support/fake_ipen_pointer_point_statics.h"
#include "base/no_destructor.h"
#include "base/notreached.h"
namespace views {
FakeIPenPointerPointStatics::FakeIPenPointerPointStatics() = default;
FakeIPenPointerPointStatics::~FakeIPenPointerPointStatics() = default;
// static
FakeIPenPointerPointStatics* FakeIPenPointerPointStatics::GetInstance() {
// This instantiation contributes to singleton lazy initialization.
static base::NoDestructor<FakeIPenPointerPointStatics> instance;
return instance.get();
}
// static
Microsoft::WRL::ComPtr<IPointerPointStatics>
FakeIPenPointerPointStatics::FakeIPenPointerPointStaticsComPtr() {
FakeIPenPointerPointStatics* instance = GetInstance();
return static_cast<Microsoft::WRL::ComPtr<IPointerPointStatics>>(instance);
}
HRESULT FakeIPenPointerPointStatics::GetCurrentPoint(
UINT32 pointer_id,
ABI::Windows::UI::Input::IPointerPoint** result) {
auto pointer_point = pointer_point_map_.find(pointer_id);
if (pointer_point == pointer_point_map_.end()) {
return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
}
// This call always return S_OK.
return pointer_point->second.CopyTo(result);
}
void FakeIPenPointerPointStatics::AddPointerPoint(
UINT32 pointer_id,
Microsoft::WRL::ComPtr<ABI::Windows::UI::Input::IPointerPoint>
pointer_point) {
pointer_point_map_[pointer_id] = pointer_point;
}
void FakeIPenPointerPointStatics::ClearPointerPointsMap() {
pointer_point_map_.clear();
}
HRESULT FakeIPenPointerPointStatics::GetIntermediatePoints(
UINT32 pointer_id,
ABI::Windows::Foundation::Collections::IVector<
ABI::Windows::UI::Input::PointerPoint*>** points) {
NOTIMPLEMENTED();
return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
}
HRESULT FakeIPenPointerPointStatics::GetCurrentPointTransformed(
UINT32 pointer_id,
ABI::Windows::UI::Input::IPointerPointTransform* t,
ABI::Windows::UI::Input::IPointerPoint** p) {
NOTIMPLEMENTED();
return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
}
HRESULT FakeIPenPointerPointStatics::GetIntermediatePointsTransformed(
UINT32 pointer_id,
ABI::Windows::UI::Input::IPointerPointTransform* t,
ABI::Windows::Foundation::Collections::IVector<
ABI::Windows::UI::Input::PointerPoint*>** points) {
NOTIMPLEMENTED();
return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/win/test_support/fake_ipen_pointer_point_statics.cc | C++ | unknown | 2,519 |
// 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_WIN_TEST_SUPPORT_FAKE_IPEN_POINTER_POINT_STATICS_H_
#define UI_VIEWS_WIN_TEST_SUPPORT_FAKE_IPEN_POINTER_POINT_STATICS_H_
#include <windows.devices.input.h>
#include <windows.foundation.collections.h>
#include <windows.ui.input.h>
#include <wrl.h>
#include <unordered_map>
#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/core_winrt_util.h"
#include "base/win/hstring_reference.h"
#include "base/win/win_util.h"
namespace views {
using ABI::Windows::UI::Input::IPointerPoint;
using ABI::Windows::UI::Input::IPointerPointStatics;
using ABI::Windows::UI::Input::IPointerPointTransform;
using ABI::Windows::UI::Input::PointerPoint;
// ABI::Windows::UI::Input::IPointerPointStatics fake implementation.
class FakeIPenPointerPointStatics final
: public Microsoft::WRL::RuntimeClass<
Microsoft::WRL::RuntimeClassFlags<
Microsoft::WRL::WinRt | Microsoft::WRL::InhibitRoOriginateError>,
IPointerPointStatics> {
public:
FakeIPenPointerPointStatics();
FakeIPenPointerPointStatics(const FakeIPenPointerPointStatics&) = delete;
FakeIPenPointerPointStatics& operator=(const FakeIPenPointerPointStatics&) =
delete;
~FakeIPenPointerPointStatics() final;
static FakeIPenPointerPointStatics* GetInstance();
static Microsoft::WRL::ComPtr<IPointerPointStatics>
FakeIPenPointerPointStaticsComPtr();
HRESULT WINAPI GetCurrentPoint(UINT32 pointer_id,
IPointerPoint** pointer_point) override;
HRESULT STDMETHODCALLTYPE GetIntermediatePoints(
UINT32 pointer_id,
ABI::Windows::Foundation::Collections::IVector<PointerPoint*>** points)
override;
HRESULT STDMETHODCALLTYPE
GetCurrentPointTransformed(UINT32 pointer_id,
IPointerPointTransform* t,
IPointerPoint**) override;
HRESULT STDMETHODCALLTYPE GetIntermediatePointsTransformed(
UINT32 pointer_id,
IPointerPointTransform* t,
ABI::Windows::Foundation::Collections::IVector<PointerPoint*>** points)
override;
// Test methods
void AddPointerPoint(UINT32 pointer_id,
Microsoft::WRL::ComPtr<IPointerPoint> pointer_point);
void ClearPointerPointsMap();
private:
std::unordered_map<
/*pointer_id=*/UINT32,
Microsoft::WRL::ComPtr<IPointerPoint>>
pointer_point_map_;
};
} // namespace views
#endif // UI_VIEWS_WIN_TEST_SUPPORT_FAKE_IPEN_POINTER_POINT_STATICS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/win/test_support/fake_ipen_pointer_point_statics.h | C++ | unknown | 2,655 |
// 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/win/test_support/fake_ipointer_point.h"
#include <combaseapi.h>
#include <wchar.h>
#include <string>
#include "base/check_op.h"
#include "base/cxx17_backports.h"
#include "base/notreached.h"
#include "base/strings/string_piece_forward.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/win_util.h"
#include "ui/views/win/test_support/fake_ipointer_point_properties.h"
using Microsoft::WRL::ComPtr;
namespace views {
FakeIPointerPoint::FakeIPointerPoint()
: properties_(Microsoft::WRL::Make<FakeIPointerPointProperties>()) {}
FakeIPointerPoint::FakeIPointerPoint(bool throw_error_in_get_properties,
bool has_usage_throws_error,
bool get_usage_throws_error,
int tsn,
int tvid)
: throw_error_in_get_properties_(throw_error_in_get_properties),
properties_(Microsoft::WRL::Make<FakeIPointerPointProperties>(
has_usage_throws_error,
get_usage_throws_error,
tsn,
tvid)) {}
FakeIPointerPoint::~FakeIPointerPoint() = default;
HRESULT FakeIPointerPoint::get_Properties(
ABI::Windows::UI::Input::IPointerPointProperties** value) {
if (throw_error_in_get_properties_) {
return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
}
properties_.CopyTo(value);
return S_OK;
}
HRESULT WINAPI FakeIPointerPoint::get_PointerDevice(
ABI::Windows::Devices::Input::IPointerDevice** value) {
NOTIMPLEMENTED();
return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
}
HRESULT WINAPI
FakeIPointerPoint::get_Position(ABI::Windows::Foundation::Point* value) {
NOTIMPLEMENTED();
return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
}
HRESULT WINAPI
FakeIPointerPoint::get_RawPosition(ABI::Windows::Foundation::Point* value) {
NOTIMPLEMENTED();
return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
}
HRESULT WINAPI FakeIPointerPoint::get_PointerId(UINT32* value) {
NOTIMPLEMENTED();
return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
}
HRESULT WINAPI FakeIPointerPoint::get_FrameId(UINT32* value) {
NOTIMPLEMENTED();
return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
}
HRESULT WINAPI FakeIPointerPoint::get_Timestamp(UINT64* value) {
NOTIMPLEMENTED();
return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
}
HRESULT WINAPI FakeIPointerPoint::get_IsInContact(boolean* value) {
NOTIMPLEMENTED();
return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/win/test_support/fake_ipointer_point.cc | C++ | unknown | 2,612 |
// 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_WIN_TEST_SUPPORT_FAKE_IPOINTER_POINT_H_
#define UI_VIEWS_WIN_TEST_SUPPORT_FAKE_IPOINTER_POINT_H_
#include <windows.devices.input.h>
#include <windows.ui.input.h>
#include <wrl.h>
#include "ui/views/win/test_support/fake_ipointer_point_properties.h"
namespace views {
// ABI::Windows::UI::Input::IPointerPoint fake implementation.
class FakeIPointerPoint final
: public Microsoft::WRL::RuntimeClass<
Microsoft::WRL::RuntimeClassFlags<
Microsoft::WRL::WinRt | Microsoft::WRL::InhibitRoOriginateError>,
ABI::Windows::UI::Input::IPointerPoint> {
public:
FakeIPointerPoint();
FakeIPointerPoint(bool throw_error_in_get_properties,
bool has_usage_throws_error = false,
bool get_usage_throws_error = false,
int tsn = 0,
int tvid = 0);
explicit FakeIPointerPoint(FakeIPointerPointProperties* p);
FakeIPointerPoint& operator=(const FakeIPointerPoint&) = delete;
~FakeIPointerPoint() override;
HRESULT WINAPI get_Properties(
ABI::Windows::UI::Input::IPointerPointProperties**
pointer_point_properties) override;
HRESULT WINAPI
get_PointerDevice(ABI::Windows::Devices::Input::IPointerDevice**) override;
HRESULT WINAPI get_Position(ABI::Windows::Foundation::Point*) override;
HRESULT WINAPI get_RawPosition(ABI::Windows::Foundation::Point*) override;
HRESULT WINAPI get_PointerId(UINT32*) override;
HRESULT WINAPI get_FrameId(UINT32*) override;
HRESULT WINAPI get_Timestamp(UINT64*) override;
HRESULT WINAPI get_IsInContact(boolean*) override;
private:
bool throw_error_in_get_properties_ = false;
Microsoft::WRL::ComPtr<FakeIPointerPointProperties> properties_;
};
} // namespace views
#endif // UI_VIEWS_WIN_TEST_SUPPORT_FAKE_IPOINTER_POINT_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/win/test_support/fake_ipointer_point.h | C++ | unknown | 1,975 |
// 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/win/test_support/fake_ipointer_point_properties.h"
#include <combaseapi.h>
#include <wchar.h>
#include <string>
#include "base/check_op.h"
#include "base/cxx17_backports.h"
#include "base/notreached.h"
#include "base/strings/string_piece_forward.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/win_util.h"
using Microsoft::WRL::ComPtr;
namespace views {
#define HID_USAGE_ID_TSN ((UINT)0x5b)
#define HID_USAGE_ID_TVID ((UINT)0x91)
FakeIPointerPointProperties::FakeIPointerPointProperties() = default;
FakeIPointerPointProperties::FakeIPointerPointProperties(
bool has_usage_throws_error,
bool get_usage_throws_error,
int tsn,
int tvid)
: has_usage_throws_error_(has_usage_throws_error),
get_usage_throws_error_(get_usage_throws_error),
tsn_(tsn),
tvid_(tvid) {}
FakeIPointerPointProperties::~FakeIPointerPointProperties() = default;
HRESULT FakeIPointerPointProperties::get_IsInverted(boolean*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_Pressure(float*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_IsEraser(boolean*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_Orientation(float*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_XTilt(float*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_YTilt(float*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_Twist(float*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_ContactRect(
ABI::Windows::Foundation::Rect*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_ContactRectRaw(
ABI::Windows::Foundation::Rect*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_TouchConfidence(boolean*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_IsLeftButtonPressed(boolean*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_IsRightButtonPressed(boolean*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_IsMiddleButtonPressed(boolean*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_MouseWheelDelta(INT32*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_IsHorizontalMouseWheel(boolean*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_IsPrimary(boolean*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_IsInRange(boolean*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_IsCanceled(boolean*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_IsBarrelButtonPressed(boolean*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_IsXButton1Pressed(boolean*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_IsXButton2Pressed(boolean*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::get_PointerUpdateKind(
ABI::Windows::UI::Input::PointerUpdateKind*) {
NOTIMPLEMENTED();
return S_OK;
}
HRESULT FakeIPointerPointProperties::HasUsage(UINT32, UINT32, boolean* value) {
if (has_usage_throws_error_) {
return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
}
*value = true;
return S_OK;
}
HRESULT FakeIPointerPointProperties::GetUsageValue(UINT32 a,
UINT32 id_type,
INT32* value) {
if (get_usage_throws_error_) {
return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
}
if (id_type == HID_USAGE_ID_TSN) {
*value = tsn();
} else if (id_type == HID_USAGE_ID_TVID) {
*value = tvid();
} else {
NOTREACHED();
}
return S_OK;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/win/test_support/fake_ipointer_point_properties.cc | C++ | unknown | 4,118 |
// 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_WIN_TEST_SUPPORT_FAKE_IPOINTER_POINT_PROPERTIES_H_
#define UI_VIEWS_WIN_TEST_SUPPORT_FAKE_IPOINTER_POINT_PROPERTIES_H_
#include <windows.devices.input.h>
#include <windows.ui.input.h>
#include <wrl.h>
namespace views {
// ABI::Windows::UI::Input::IPointerPointProperties fake implementation.
class FakeIPointerPointProperties final
: public Microsoft::WRL::RuntimeClass<
Microsoft::WRL::RuntimeClassFlags<
Microsoft::WRL::WinRt | Microsoft::WRL::InhibitRoOriginateError>,
ABI::Windows::UI::Input::IPointerPointProperties> {
public:
FakeIPointerPointProperties();
FakeIPointerPointProperties(bool has_usage_throws_error,
bool get_usage_throws_error,
int tsn,
int tvid);
FakeIPointerPointProperties& operator=(const FakeIPointerPointProperties&) =
delete;
~FakeIPointerPointProperties() override;
HRESULT STDMETHODCALLTYPE get_IsInverted(boolean*) override;
HRESULT STDMETHODCALLTYPE get_Pressure(float*) override;
HRESULT STDMETHODCALLTYPE get_IsEraser(boolean*) override;
HRESULT STDMETHODCALLTYPE get_Orientation(float*) override;
HRESULT STDMETHODCALLTYPE get_XTilt(float*) override;
HRESULT STDMETHODCALLTYPE get_YTilt(float*) override;
HRESULT STDMETHODCALLTYPE get_Twist(float*) override;
HRESULT STDMETHODCALLTYPE
get_ContactRect(ABI::Windows::Foundation::Rect*) override;
HRESULT STDMETHODCALLTYPE
get_ContactRectRaw(ABI::Windows::Foundation::Rect*) override;
HRESULT STDMETHODCALLTYPE get_TouchConfidence(boolean*) override;
HRESULT STDMETHODCALLTYPE get_IsLeftButtonPressed(boolean*) override;
HRESULT STDMETHODCALLTYPE get_IsRightButtonPressed(boolean*) override;
HRESULT STDMETHODCALLTYPE get_IsMiddleButtonPressed(boolean*) override;
HRESULT STDMETHODCALLTYPE get_MouseWheelDelta(INT32*) override;
HRESULT STDMETHODCALLTYPE get_IsHorizontalMouseWheel(boolean*) override;
HRESULT STDMETHODCALLTYPE get_IsPrimary(boolean*) override;
HRESULT STDMETHODCALLTYPE get_IsInRange(boolean*) override;
HRESULT STDMETHODCALLTYPE get_IsCanceled(boolean*) override;
HRESULT STDMETHODCALLTYPE get_IsBarrelButtonPressed(boolean*) override;
HRESULT STDMETHODCALLTYPE get_IsXButton1Pressed(boolean*) override;
HRESULT STDMETHODCALLTYPE get_IsXButton2Pressed(boolean*) override;
HRESULT STDMETHODCALLTYPE
get_PointerUpdateKind(ABI::Windows::UI::Input::PointerUpdateKind*) override;
HRESULT STDMETHODCALLTYPE HasUsage(UINT32, UINT32, boolean*) override;
HRESULT STDMETHODCALLTYPE GetUsageValue(UINT32, UINT32, INT32*) override;
int tsn() { return tsn_; }
int tvid() { return tvid_; }
private:
bool has_usage_throws_error_ = false;
bool get_usage_throws_error_ = false;
int tsn_;
int tvid_;
};
} // namespace views
#endif // UI_VIEWS_WIN_TEST_SUPPORT_FAKE_IPOINTER_POINT_PROPERTIES_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/win/test_support/fake_ipointer_point_properties.h | C++ | unknown | 3,061 |
// 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/window/caption_button_layout_constants.h"
#include "build/chromeos_buildflags.h"
#include "ui/base/pointer/touch_ui_controller.h"
#include "ui/gfx/geometry/size.h"
#if BUILDFLAG(IS_CHROMEOS)
#include "chromeos/constants/chromeos_features.h"
#endif // BUILDFLAG(IS_CHROMEOS)
namespace views {
gfx::Size GetCaptionButtonLayoutSize(CaptionButtonLayoutSize size) {
#if BUILDFLAG(IS_CHROMEOS)
if (chromeos::features::IsJellyrollEnabled()) {
return gfx::Size(
36,
size == CaptionButtonLayoutSize::kBrowserCaptionMaximized ? 34 : 40);
}
#endif // BUILDFLAG(IS_CHROMEOS)
if (size == CaptionButtonLayoutSize::kNonBrowserCaption) {
return gfx::Size(32, 32);
}
// |kBrowserMaximizedCaptionButtonHeight| should be kept in sync with those
// for TAB_HEIGHT in // chrome/browser/ui/layout_constants.cc.
// TODO(pkasting): Ideally these values should be obtained from a common
// location.
int height = ui::TouchUiController::Get()->touch_ui() ? 41 : 34;
if (size == CaptionButtonLayoutSize::kBrowserCaptionRestored) {
// Restored window titlebars are 8 DIP taller than maximized.
height += 8;
}
return gfx::Size(32, height);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/window/caption_button_layout_constants.cc | C++ | unknown | 1,364 |
// 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_WINDOW_CAPTION_BUTTON_LAYOUT_CONSTANTS_H_
#define UI_VIEWS_WINDOW_CAPTION_BUTTON_LAYOUT_CONSTANTS_H_
#include "ui/views/views_export.h"
namespace gfx {
class Size;
} // namespace gfx
namespace views {
enum class CaptionButtonLayoutSize {
// Size of a caption button in a maximized browser window.
kBrowserCaptionMaximized,
// Size of a caption button in a restored browser window.
kBrowserCaptionRestored,
// Size of a caption button in a non-browser window.
kNonBrowserCaption,
};
// Default radius of caption button ink drop highlight and mask.
constexpr int kCaptionButtonInkDropDefaultCornerRadius = 14;
// Caption button width.
constexpr int kCaptionButtonWidth = 32;
// Calculates the preferred size of an MD-style frame caption button. Only used
// on ChromeOS and desktop Linux.
VIEWS_EXPORT gfx::Size GetCaptionButtonLayoutSize(CaptionButtonLayoutSize size);
} // namespace views
#endif // UI_VIEWS_WINDOW_CAPTION_BUTTON_LAYOUT_CONSTANTS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/window/caption_button_layout_constants.h | C++ | unknown | 1,138 |
// 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_WINDOW_CAPTION_BUTTON_TYPES_H_
#define UI_VIEWS_WINDOW_CAPTION_BUTTON_TYPES_H_
namespace views {
// These are the icon types that a caption button can have. The size button's
// action (SnapType) can be different from its icon.
enum CaptionButtonIcon {
CAPTION_BUTTON_ICON_MINIMIZE,
CAPTION_BUTTON_ICON_MAXIMIZE_RESTORE,
CAPTION_BUTTON_ICON_CLOSE,
CAPTION_BUTTON_ICON_LEFT_TOP_SNAPPED,
CAPTION_BUTTON_ICON_RIGHT_BOTTOM_SNAPPED,
CAPTION_BUTTON_ICON_BACK,
CAPTION_BUTTON_ICON_LOCATION,
CAPTION_BUTTON_ICON_MENU,
CAPTION_BUTTON_ICON_ZOOM,
CAPTION_BUTTON_ICON_CENTER,
CAPTION_BUTTON_ICON_FLOAT,
// The custom icon type allows clients to instantiate a caption button that is
// specific to their use case (e.g. tab search caption button in the browser
// window frame).
CAPTION_BUTTON_ICON_CUSTOM,
CAPTION_BUTTON_ICON_COUNT,
};
} // namespace views
#endif // UI_VIEWS_WINDOW_CAPTION_BUTTON_TYPES_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/window/caption_button_types.h | C++ | unknown | 1,093 |
// 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/window/client_view.h"
#include <memory>
#include "base/check.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/hit_test.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
namespace views {
///////////////////////////////////////////////////////////////////////////////
// ClientView, public:
ClientView::ClientView(Widget* widget, View* contents_view)
: contents_view_(contents_view) {
SetLayoutManager(std::make_unique<views::FillLayout>());
}
int ClientView::NonClientHitTest(const gfx::Point& point) {
return bounds().Contains(point) ? HTCLIENT : HTNOWHERE;
}
CloseRequestResult ClientView::OnWindowCloseRequested() {
return CloseRequestResult::kCanClose;
}
void ClientView::WidgetClosing() {}
///////////////////////////////////////////////////////////////////////////////
// ClientView, View overrides:
gfx::Size ClientView::CalculatePreferredSize() const {
// |contents_view_| is allowed to be NULL up until the point where this view
// is attached to a Container.
if (!contents_view_)
return gfx::Size();
return contents_view_->GetPreferredSize();
}
int ClientView::GetHeightForWidth(int width) const {
// |contents_view_| is allowed to be NULL up until the point where this view
// is attached to a Container.
if (!contents_view_)
return 0;
return contents_view_->GetHeightForWidth(width);
}
gfx::Size ClientView::GetMaximumSize() const {
// |contents_view_| is allowed to be NULL up until the point where this view
// is attached to a Container.
return contents_view_ ? contents_view_->GetMaximumSize() : gfx::Size();
}
gfx::Size ClientView::GetMinimumSize() const {
// |contents_view_| is allowed to be NULL up until the point where this view
// is attached to a Container.
return contents_view_ ? contents_view_->GetMinimumSize() : gfx::Size();
}
void ClientView::GetAccessibleNodeData(ui::AXNodeData* node_data) {
node_data->role = ax::mojom::Role::kClient;
}
void ClientView::OnBoundsChanged(const gfx::Rect& previous_bounds) {
// Overridden to do nothing. The NonClientView manually calls Layout on the
// ClientView when it is itself laid out, see comment in
// NonClientView::Layout.
}
void ClientView::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
if (details.is_add && details.child == this) {
DCHECK(GetWidget());
DCHECK(contents_view_); // |contents_view_| must be valid now!
// Insert |contents_view_| at index 0 so it is first in the focus chain.
// (the OK/Cancel buttons are inserted before contents_view_)
// TODO(weili): This seems fragile and can be refactored.
// Tracked at https://crbug.com/1012466.
AddChildViewAt(contents_view_.get(), 0);
}
}
BEGIN_METADATA(ClientView, View)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/window/client_view.cc | C++ | unknown | 3,122 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WINDOW_CLIENT_VIEW_H_
#define UI_VIEWS_WINDOW_CLIENT_VIEW_H_
#include "base/memory/raw_ptr.h"
#include "ui/views/metadata/view_factory.h"
#include "ui/views/view.h"
namespace views {
class Widget;
enum class CloseRequestResult;
///////////////////////////////////////////////////////////////////////////////
// ClientView
//
// A ClientView is a View subclass that is used to occupy the "client area"
// of a widget. It provides basic information to the widget that contains it
// such as non-client hit testing information, sizing etc. Sub-classes of
// ClientView are used to create more elaborate contents.
class VIEWS_EXPORT ClientView : public View {
public:
METADATA_HEADER(ClientView);
// Constructs a ClientView object for the specified widget with the specified
// contents. Since this object is created during the process of creating
// |widget|, |contents_view| must be valid if you want the initial size of
// the widget to be based on |contents_view|'s preferred size.
ClientView(Widget* widget, View* contents_view);
~ClientView() override = default;
// Returned value signals whether the Widget can be closed. Specialized
// ClientView subclasses can override this default behavior to allow the
// close to be blocked until the user corrects mistakes, accepts a warning
// dialog, etc.
virtual CloseRequestResult OnWindowCloseRequested();
// Notification that the widget is closing.
virtual void WidgetClosing();
// Tests to see if the specified point (in view coordinates) is within the
// bounds of this view. If so, it returns HTCLIENT in this default
// implementation. If it is outside the bounds of this view, this must return
// HTNOWHERE to tell the caller to do further processing to determine where
// in the non-client area it is (if it is).
// Subclasses of ClientView can extend this logic by overriding this method
// to detect if regions within the client area count as parts of the "non-
// client" area. A good example of this is the size box at the bottom right
// corner of resizable dialog boxes.
virtual int NonClientHitTest(const gfx::Point& point);
// Overridden from View:
gfx::Size CalculatePreferredSize() const override;
int GetHeightForWidth(int width) const override;
gfx::Size GetMinimumSize() const override;
gfx::Size GetMaximumSize() const override;
protected:
// Overridden from View:
void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
void OnBoundsChanged(const gfx::Rect& previous_bounds) override;
void ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) override;
// Accessors for private data members.
View* contents_view() const { return contents_view_; }
void set_contents_view(View* contents_view) {
contents_view_ = contents_view;
}
private:
// The View that this ClientView contains.
raw_ptr<View, DanglingUntriaged> contents_view_;
};
BEGIN_VIEW_BUILDER(VIEWS_EXPORT, ClientView, View)
END_VIEW_BUILDER
} // namespace views
DEFINE_VIEW_BUILDER(VIEWS_EXPORT, ClientView)
#endif // UI_VIEWS_WINDOW_CLIENT_VIEW_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/window/client_view.h | C++ | unknown | 3,272 |
// 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/window/custom_frame_view.h"
#include <algorithm>
#include <utility>
#include <vector>
#include "base/containers/adapters.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "third_party/skia/include/core/SkPath.h"
#include "ui/base/hit_test.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/models/image_model.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/font.h"
#include "ui/gfx/font_list.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/image/image.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/resources/grit/views_resources.h"
#include "ui/views/views_delegate.h"
#include "ui/views/widget/native_widget_private.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/client_view.h"
#include "ui/views/window/frame_background.h"
#include "ui/views/window/window_button_order_provider.h"
#include "ui/views/window/window_resources.h"
#include "ui/views/window/window_shape.h"
#if BUILDFLAG(IS_WIN)
#include "ui/display/win/screen_win.h"
#include "ui/gfx/system_fonts_win.h"
#endif
namespace views {
namespace {
// The frame border is only visible in restored mode and is hardcoded to 4 px on
// each side regardless of the system window border size.
constexpr int kFrameBorderThickness = 4;
// In the window corners, the resize areas don't actually expand bigger, but the
// 16 px at the end of each edge triggers diagonal resizing.
constexpr int kResizeAreaCornerSize = 16;
// The titlebar never shrinks too short to show the caption button plus some
// padding below it.
constexpr int kCaptionButtonHeightWithPadding = 19;
// The titlebar has a 2 px 3D edge along the top and bottom.
constexpr int kTitlebarTopAndBottomEdgeThickness = 2;
// The icon is inset 2 px from the left frame border.
constexpr int kIconLeftSpacing = 2;
// The space between the window icon and the title text.
constexpr int kTitleIconOffsetX = 4;
// The space between the title text and the caption buttons.
constexpr int kTitleCaptionSpacing = 5;
void LayoutButton(ImageButton* button, const gfx::Rect& bounds) {
button->SetVisible(true);
button->SetImageVerticalAlignment(ImageButton::ALIGN_BOTTOM);
button->SetBoundsRect(bounds);
}
} // namespace
CustomFrameView::CustomFrameView(Widget* frame)
: frame_(frame), frame_background_(new FrameBackground()) {
close_button_ = InitWindowCaptionButton(
base::BindRepeating(&Widget::CloseWithReason, base::Unretained(frame_),
views::Widget::ClosedReason::kCloseButtonClicked),
IDS_APP_ACCNAME_CLOSE, IDR_CLOSE, IDR_CLOSE_H, IDR_CLOSE_P);
minimize_button_ = InitWindowCaptionButton(
base::BindRepeating(&Widget::Minimize, base::Unretained(frame_)),
IDS_APP_ACCNAME_MINIMIZE, IDR_MINIMIZE, IDR_MINIMIZE_H, IDR_MINIMIZE_P);
maximize_button_ = InitWindowCaptionButton(
base::BindRepeating(&Widget::Maximize, base::Unretained(frame_)),
IDS_APP_ACCNAME_MAXIMIZE, IDR_MAXIMIZE, IDR_MAXIMIZE_H, IDR_MAXIMIZE_P);
restore_button_ = InitWindowCaptionButton(
base::BindRepeating(&Widget::Restore, base::Unretained(frame_)),
IDS_APP_ACCNAME_RESTORE, IDR_RESTORE, IDR_RESTORE_H, IDR_RESTORE_P);
if (frame_->widget_delegate()->ShouldShowWindowIcon()) {
window_icon_ =
AddChildView(std::make_unique<ImageButton>(Button::PressedCallback()));
// `window_icon_` does not need to be focusable as it is not used here as a
// button and is not interactive.
window_icon_->SetFocusBehavior(FocusBehavior::NEVER);
}
}
CustomFrameView::~CustomFrameView() = default;
gfx::Rect CustomFrameView::GetBoundsForClientView() const {
return client_view_bounds_;
}
gfx::Rect CustomFrameView::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
int top_height = NonClientTopBorderHeight();
int border_thickness = NonClientBorderThickness();
return gfx::Rect(client_bounds.x() - border_thickness,
client_bounds.y() - top_height,
client_bounds.width() + (2 * border_thickness),
client_bounds.height() + top_height + border_thickness);
}
int CustomFrameView::NonClientHitTest(const gfx::Point& point) {
// Sanity check.
if (!bounds().Contains(point))
return HTNOWHERE;
int frame_component = frame_->client_view()->NonClientHitTest(point);
// See if we're in the sysmenu region. (We check the ClientView first to be
// consistent with OpaqueBrowserFrameView; it's not really necessary here.)
gfx::Rect sysmenu_rect(IconBounds());
// In maximized mode we extend the rect to the screen corner to take advantage
// of Fitts' Law.
if (frame_->IsMaximized())
sysmenu_rect.SetRect(0, 0, sysmenu_rect.right(), sysmenu_rect.bottom());
sysmenu_rect.set_x(GetMirroredXForRect(sysmenu_rect));
if (sysmenu_rect.Contains(point))
return (frame_component == HTCLIENT) ? HTCLIENT : HTSYSMENU;
if (frame_component != HTNOWHERE)
return frame_component;
// Then see if the point is within any of the window controls.
if (close_button_->GetMirroredBounds().Contains(point))
return HTCLOSE;
if (restore_button_->GetMirroredBounds().Contains(point))
return HTMAXBUTTON;
if (maximize_button_->GetMirroredBounds().Contains(point))
return HTMAXBUTTON;
if (minimize_button_->GetMirroredBounds().Contains(point))
return HTMINBUTTON;
if (window_icon_ && window_icon_->GetMirroredBounds().Contains(point))
return HTSYSMENU;
gfx::Insets resize_border(NonClientBorderThickness());
// The top resize border has extra thickness.
resize_border.set_top(FrameBorderThickness());
int window_component = GetHTComponentForFrame(
point, resize_border, kResizeAreaCornerSize, kResizeAreaCornerSize,
frame_->widget_delegate()->CanResize());
// Fall back to the caption if no other component matches.
return (window_component == HTNOWHERE) ? HTCAPTION : window_component;
}
void CustomFrameView::GetWindowMask(const gfx::Size& size,
SkPath* window_mask) {
DCHECK(window_mask);
if (frame_->IsMaximized() || !ShouldShowTitleBarAndBorder())
return;
GetDefaultWindowMask(size, window_mask);
}
void CustomFrameView::ResetWindowControls() {
restore_button_->SetState(Button::STATE_NORMAL);
minimize_button_->SetState(Button::STATE_NORMAL);
maximize_button_->SetState(Button::STATE_NORMAL);
// The close button isn't affected by this constraint.
}
void CustomFrameView::UpdateWindowIcon() {
if (window_icon_)
window_icon_->SchedulePaint();
}
void CustomFrameView::UpdateWindowTitle() {
if (frame_->widget_delegate()->ShouldShowWindowTitle() &&
// If this is still unset, we haven't laid out window controls yet.
maximum_title_bar_x_ > -1) {
LayoutTitleBar();
SchedulePaintInRect(title_bounds_);
}
}
void CustomFrameView::SizeConstraintsChanged() {
ResetWindowControls();
LayoutWindowControls();
}
void CustomFrameView::OnPaint(gfx::Canvas* canvas) {
if (!ShouldShowTitleBarAndBorder())
return;
frame_background_->set_frame_color(GetFrameColor());
frame_background_->set_use_custom_frame(true);
frame_background_->set_is_active(ShouldPaintAsActive());
const gfx::ImageSkia frame_image = GetFrameImage();
frame_background_->set_theme_image(frame_image);
frame_background_->set_top_area_height(frame_image.height());
if (frame_->IsMaximized())
PaintMaximizedFrameBorder(canvas);
else
PaintRestoredFrameBorder(canvas);
PaintTitleBar(canvas);
if (ShouldShowClientEdge())
PaintRestoredClientEdge(canvas);
}
void CustomFrameView::Layout() {
if (ShouldShowTitleBarAndBorder()) {
LayoutWindowControls();
LayoutTitleBar();
}
LayoutClientView();
NonClientFrameView::Layout();
}
gfx::Size CustomFrameView::CalculatePreferredSize() const {
return frame_->non_client_view()
->GetWindowBoundsForClientBounds(
gfx::Rect(frame_->client_view()->GetPreferredSize()))
.size();
}
gfx::Size CustomFrameView::GetMinimumSize() const {
return frame_->non_client_view()
->GetWindowBoundsForClientBounds(
gfx::Rect(frame_->client_view()->GetMinimumSize()))
.size();
}
gfx::Size CustomFrameView::GetMaximumSize() const {
gfx::Size max_size = frame_->client_view()->GetMaximumSize();
gfx::Size converted_size =
frame_->non_client_view()
->GetWindowBoundsForClientBounds(gfx::Rect(max_size))
.size();
return gfx::Size(max_size.width() == 0 ? 0 : converted_size.width(),
max_size.height() == 0 ? 0 : converted_size.height());
}
int CustomFrameView::FrameBorderThickness() const {
return frame_->IsMaximized() ? 0 : kFrameBorderThickness;
}
int CustomFrameView::NonClientBorderThickness() const {
// In maximized mode, we don't show a client edge.
return FrameBorderThickness() +
(ShouldShowClientEdge() ? kClientEdgeThickness : 0);
}
int CustomFrameView::NonClientTopBorderHeight() const {
return std::max(FrameBorderThickness() + IconSize(),
CaptionButtonY() + kCaptionButtonHeightWithPadding) +
TitlebarBottomThickness();
}
int CustomFrameView::CaptionButtonY() const {
// Maximized buttons start at window top so that even if their images aren't
// drawn flush with the screen edge, they still obey Fitts' Law.
// 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)
return FrameBorderThickness();
#else
return frame_->IsMaximized() ? FrameBorderThickness() : kFrameShadowThickness;
#endif
}
int CustomFrameView::TitlebarBottomThickness() const {
return kTitlebarTopAndBottomEdgeThickness +
(ShouldShowClientEdge() ? kClientEdgeThickness : 0);
}
int CustomFrameView::IconSize() const {
#if BUILDFLAG(IS_WIN)
// This metric scales up if either the titlebar height or the titlebar font
// size are increased.
return display::win::ScreenWin::GetSystemMetricsInDIP(SM_CYSMICON);
#else
// The icon never shrinks below 16 px on a side.
constexpr int kIconMinimumSize = 16;
return std::max(GetWindowTitleFontList().GetHeight(), kIconMinimumSize);
#endif
}
gfx::Rect CustomFrameView::IconBounds() const {
int size = IconSize();
int frame_thickness = FrameBorderThickness();
// Our frame border has a different "3D look" than Windows'. Theirs has a
// more complex gradient on the top that they push their icon/title below;
// then the maximized window cuts this off and the icon/title are centered
// in the remaining space. Because the apparent shape of our border is
// simpler, using the same positioning makes things look slightly uncentered
// with restored windows, so when the window is restored, instead of
// calculating the remaining space from below the frame border, we calculate
// from below the 3D edge.
int unavailable_px_at_top = frame_->IsMaximized()
? frame_thickness
: kTitlebarTopAndBottomEdgeThickness;
// When the icon is shorter than the minimum space we reserve for the caption
// button, we vertically center it. We want to bias rounding to put extra
// space above the icon, since the 3D edge (+ client edge, for restored
// windows) below looks (to the eye) more like additional space than does the
// 3D edge (or nothing at all, for maximized windows) above; hence the +1.
int y = unavailable_px_at_top +
(NonClientTopBorderHeight() - unavailable_px_at_top - size -
TitlebarBottomThickness() + 1) /
2;
return gfx::Rect(frame_thickness + kIconLeftSpacing + minimum_title_bar_x_, y,
size, size);
}
bool CustomFrameView::ShouldShowTitleBarAndBorder() const {
return !frame_->IsFullscreen() &&
!ViewsDelegate::GetInstance()->WindowManagerProvidesTitleBar(
frame_->IsMaximized());
}
bool CustomFrameView::ShouldShowClientEdge() const {
return !frame_->IsMaximized() && ShouldShowTitleBarAndBorder();
}
void CustomFrameView::PaintRestoredFrameBorder(gfx::Canvas* canvas) {
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
frame_background_->SetCornerImages(
rb.GetImageNamed(IDR_WINDOW_TOP_LEFT_CORNER).ToImageSkia(),
rb.GetImageNamed(IDR_WINDOW_TOP_RIGHT_CORNER).ToImageSkia(),
rb.GetImageNamed(IDR_WINDOW_BOTTOM_LEFT_CORNER).ToImageSkia(),
rb.GetImageNamed(IDR_WINDOW_BOTTOM_RIGHT_CORNER).ToImageSkia());
frame_background_->SetSideImages(
rb.GetImageNamed(IDR_WINDOW_LEFT_SIDE).ToImageSkia(),
rb.GetImageNamed(IDR_WINDOW_TOP_CENTER).ToImageSkia(),
rb.GetImageNamed(IDR_WINDOW_RIGHT_SIDE).ToImageSkia(),
rb.GetImageNamed(IDR_WINDOW_BOTTOM_CENTER).ToImageSkia());
frame_background_->PaintRestored(canvas, this);
}
void CustomFrameView::PaintMaximizedFrameBorder(gfx::Canvas* canvas) {
frame_background_->PaintMaximized(canvas, this);
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
// TODO(jamescook): Migrate this into FrameBackground.
// The bottom of the titlebar actually comes from the top of the Client Edge
// graphic, with the actual client edge clipped off the bottom.
const gfx::ImageSkia* titlebar_bottom =
rb.GetImageNamed(IDR_APP_TOP_CENTER).ToImageSkia();
int edge_height = titlebar_bottom->height() -
(ShouldShowClientEdge() ? kClientEdgeThickness : 0);
canvas->TileImageInt(*titlebar_bottom, 0,
frame_->client_view()->y() - edge_height, width(),
edge_height);
}
void CustomFrameView::PaintTitleBar(gfx::Canvas* canvas) {
WidgetDelegate* delegate = frame_->widget_delegate();
// It seems like in some conditions we can be asked to paint after the window
// that contains us is WM_DESTROYed. At this point, our delegate is NULL. The
// correct long term fix may be to shut down the RootView in WM_DESTROY.
if (!delegate || !delegate->ShouldShowWindowTitle())
return;
gfx::Rect rect = title_bounds_;
rect.set_x(GetMirroredXForRect(title_bounds_));
canvas->DrawStringRect(
delegate->GetWindowTitle(), GetWindowTitleFontList(),
GetColorProvider()->GetColor(ui::kColorCustomFrameCaptionForeground),
rect);
}
void CustomFrameView::PaintRestoredClientEdge(gfx::Canvas* canvas) {
gfx::Rect client_area_bounds = frame_->client_view()->bounds();
// The shadows have a 1 pixel gap on the inside, so draw them 1 pixel inwards.
gfx::Rect shadowed_area_bounds = client_area_bounds;
shadowed_area_bounds.Inset(gfx::Insets(1));
int shadowed_area_top = shadowed_area_bounds.y();
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
// Top: left, center, right sides.
const gfx::ImageSkia* top_left = rb.GetImageSkiaNamed(IDR_APP_TOP_LEFT);
const gfx::ImageSkia* top_center = rb.GetImageSkiaNamed(IDR_APP_TOP_CENTER);
const gfx::ImageSkia* top_right = rb.GetImageSkiaNamed(IDR_APP_TOP_RIGHT);
int top_edge_y = shadowed_area_top - top_center->height();
canvas->DrawImageInt(*top_left, shadowed_area_bounds.x() - top_left->width(),
top_edge_y);
canvas->TileImageInt(*top_center, shadowed_area_bounds.x(), top_edge_y,
shadowed_area_bounds.width(), top_center->height());
canvas->DrawImageInt(*top_right, shadowed_area_bounds.right(), top_edge_y);
// Right side.
const gfx::ImageSkia* right = rb.GetImageSkiaNamed(IDR_CONTENT_RIGHT_SIDE);
int shadowed_area_bottom =
std::max(shadowed_area_top, shadowed_area_bounds.bottom());
int shadowed_area_height = shadowed_area_bottom - shadowed_area_top;
canvas->TileImageInt(*right, shadowed_area_bounds.right(), shadowed_area_top,
right->width(), shadowed_area_height);
// Bottom: left, center, right sides.
const gfx::ImageSkia* bottom_left =
rb.GetImageSkiaNamed(IDR_CONTENT_BOTTOM_LEFT_CORNER);
const gfx::ImageSkia* bottom_center =
rb.GetImageSkiaNamed(IDR_CONTENT_BOTTOM_CENTER);
const gfx::ImageSkia* bottom_right =
rb.GetImageSkiaNamed(IDR_CONTENT_BOTTOM_RIGHT_CORNER);
canvas->DrawImageInt(*bottom_left,
shadowed_area_bounds.x() - bottom_left->width(),
shadowed_area_bottom);
canvas->TileImageInt(*bottom_center, shadowed_area_bounds.x(),
shadowed_area_bottom, shadowed_area_bounds.width(),
bottom_right->height());
canvas->DrawImageInt(*bottom_right, shadowed_area_bounds.right(),
shadowed_area_bottom);
// Left side.
const gfx::ImageSkia* left = rb.GetImageSkiaNamed(IDR_CONTENT_LEFT_SIDE);
canvas->TileImageInt(*left, shadowed_area_bounds.x() - left->width(),
shadowed_area_top, left->width(), shadowed_area_height);
}
SkColor CustomFrameView::GetFrameColor() const {
return GetColorProvider()->GetColor(
frame_->IsActive() ? ui::kColorFrameActive : ui::kColorFrameInactive);
}
gfx::ImageSkia CustomFrameView::GetFrameImage() const {
return *ui::ResourceBundle::GetSharedInstance()
.GetImageNamed(frame_->IsActive() ? IDR_FRAME
: IDR_FRAME_INACTIVE)
.ToImageSkia();
}
void CustomFrameView::LayoutWindowControls() {
minimum_title_bar_x_ = 0;
maximum_title_bar_x_ = width();
if (bounds().IsEmpty())
return;
int caption_y = CaptionButtonY();
bool is_maximized = frame_->IsMaximized();
// There should always be the same number of non-shadow pixels visible to the
// side of the caption buttons. In maximized mode we extend the edge button
// to the screen corner to obey Fitts' Law.
int extra_width =
is_maximized ? (kFrameBorderThickness - kFrameShadowThickness) : 0;
int next_button_x = FrameBorderThickness();
bool is_restored = !is_maximized && !frame_->IsMinimized();
ImageButton* invisible_button =
is_restored ? restore_button_.get() : maximize_button_.get();
invisible_button->SetVisible(false);
WindowButtonOrderProvider* button_order =
WindowButtonOrderProvider::GetInstance();
const std::vector<views::FrameButton>& leading_buttons =
button_order->leading_buttons();
const std::vector<views::FrameButton>& trailing_buttons =
button_order->trailing_buttons();
ImageButton* button = nullptr;
for (auto frame_button : leading_buttons) {
button = GetImageButton(frame_button);
if (!button)
continue;
gfx::Rect target_bounds(gfx::Point(next_button_x, caption_y),
button->GetPreferredSize());
if (frame_button == leading_buttons.front())
target_bounds.set_width(target_bounds.width() + extra_width);
LayoutButton(button, target_bounds);
next_button_x += button->width();
minimum_title_bar_x_ = std::min(width(), next_button_x);
}
// Trailing buttions are laid out in a RTL fashion
next_button_x = width() - FrameBorderThickness();
for (auto frame_button : base::Reversed(trailing_buttons)) {
button = GetImageButton(frame_button);
if (!button)
continue;
gfx::Rect target_bounds(gfx::Point(next_button_x, caption_y),
button->GetPreferredSize());
if (frame_button == trailing_buttons.back())
target_bounds.set_width(target_bounds.width() + extra_width);
target_bounds.Offset(-target_bounds.width(), 0);
LayoutButton(button, target_bounds);
next_button_x = button->x();
maximum_title_bar_x_ = std::max(minimum_title_bar_x_, next_button_x);
}
}
void CustomFrameView::LayoutTitleBar() {
DCHECK_GE(maximum_title_bar_x_, 0);
// The window title position is calculated based on the icon position, even
// when there is no icon.
gfx::Rect icon_bounds(IconBounds());
bool show_window_icon = window_icon_ != nullptr;
if (show_window_icon)
window_icon_->SetBoundsRect(icon_bounds);
if (!frame_->widget_delegate()->ShouldShowWindowTitle())
return;
// The offset between the window left edge and the title text.
int title_x = show_window_icon ? icon_bounds.right() + kTitleIconOffsetX
: icon_bounds.x();
int title_height = GetWindowTitleFontList().GetHeight();
// We bias the title position so that when the difference between the icon and
// title heights is odd, the extra pixel of the title is above the vertical
// midline rather than below. This compensates for how the icon is already
// biased downwards (see IconBounds()) and helps prevent descenders on the
// title from overlapping the 3D edge at the bottom of the titlebar.
title_bounds_.SetRect(
title_x,
icon_bounds.y() + ((icon_bounds.height() - title_height - 1) / 2),
std::max(0, maximum_title_bar_x_ - kTitleCaptionSpacing - title_x),
title_height);
}
void CustomFrameView::LayoutClientView() {
if (!ShouldShowTitleBarAndBorder()) {
client_view_bounds_ = bounds();
return;
}
int top_height = NonClientTopBorderHeight();
int border_thickness = NonClientBorderThickness();
client_view_bounds_.SetRect(
border_thickness, top_height,
std::max(0, width() - (2 * border_thickness)),
std::max(0, height() - top_height - border_thickness));
}
ImageButton* CustomFrameView::InitWindowCaptionButton(
Button::PressedCallback callback,
int accessibility_string_id,
int normal_image_id,
int hot_image_id,
int pushed_image_id) {
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
ImageButton* button =
AddChildView(std::make_unique<ImageButton>(std::move(callback)));
button->SetFocusBehavior(FocusBehavior::ACCESSIBLE_ONLY);
button->SetAccessibleName(l10n_util::GetStringUTF16(accessibility_string_id));
button->SetImageModel(
Button::STATE_NORMAL,
ui::ImageModel::FromImage(rb.GetImageNamed(normal_image_id)));
button->SetImageModel(
Button::STATE_HOVERED,
ui::ImageModel::FromImage(rb.GetImageNamed(hot_image_id)));
button->SetImageModel(
Button::STATE_PRESSED,
ui::ImageModel::FromImage(rb.GetImageNamed(pushed_image_id)));
return button;
}
ImageButton* CustomFrameView::GetImageButton(views::FrameButton frame_button) {
ImageButton* button = nullptr;
switch (frame_button) {
case views::FrameButton::kMinimize: {
button = minimize_button_;
// If we should not show the minimize button, then we return NULL as we
// don't want this button to become visible and to be laid out.
bool should_show = frame_->widget_delegate()->CanMinimize();
button->SetVisible(should_show);
if (!should_show)
return nullptr;
break;
}
case views::FrameButton::kMaximize: {
bool is_restored = !frame_->IsMaximized() && !frame_->IsMinimized();
button = is_restored ? maximize_button_.get() : restore_button_.get();
// If we should not show the maximize/restore button, then we return
// NULL as we don't want this button to become visible and to be laid
// out.
bool should_show = frame_->widget_delegate()->CanMaximize();
button->SetVisible(should_show);
if (!should_show)
return nullptr;
break;
}
case views::FrameButton::kClose: {
button = close_button_;
break;
}
}
return button;
}
// static
gfx::FontList CustomFrameView::GetWindowTitleFontList() {
#if BUILDFLAG(IS_WIN)
return gfx::FontList(gfx::win::GetSystemFont(gfx::win::SystemFont::kCaption));
#else
return gfx::FontList();
#endif
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/window/custom_frame_view.cc | C++ | unknown | 24,014 |
// 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_WINDOW_CUSTOM_FRAME_VIEW_H_
#define UI_VIEWS_WINDOW_CUSTOM_FRAME_VIEW_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/frame_buttons.h"
#include "ui/views/window/non_client_view.h"
namespace gfx {
class FontList;
}
namespace views {
class FrameBackground;
class ImageButton;
class Widget;
///////////////////////////////////////////////////////////////////////////////
//
// CustomFrameView
//
// A view that provides the non client frame for Windows. This means
// rendering the non-standard window caption, border, and controls.
//
////////////////////////////////////////////////////////////////////////////////
class VIEWS_EXPORT CustomFrameView : public NonClientFrameView {
public:
explicit CustomFrameView(Widget* frame);
CustomFrameView(const CustomFrameView&) = delete;
CustomFrameView& operator=(const CustomFrameView&) = delete;
~CustomFrameView() override;
// Overridden from NonClientFrameView:
gfx::Rect GetBoundsForClientView() const override;
gfx::Rect GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const override;
int NonClientHitTest(const gfx::Point& point) override;
void GetWindowMask(const gfx::Size& size, SkPath* window_mask) override;
void ResetWindowControls() override;
void UpdateWindowIcon() override;
void UpdateWindowTitle() override;
void SizeConstraintsChanged() override;
// Overridden from View:
void OnPaint(gfx::Canvas* canvas) override;
void Layout() override;
gfx::Size CalculatePreferredSize() const override;
gfx::Size GetMinimumSize() const override;
gfx::Size GetMaximumSize() const override;
// Returns the font list to use in the window's title bar.
// TODO(https://crbug.com/968860): Move this into the typography provider.
static gfx::FontList GetWindowTitleFontList();
private:
friend class CustomFrameViewTest;
// Returns the thickness of the border that makes up the window frame edges.
// This does not include any client edge.
int FrameBorderThickness() const;
// Returns the thickness of the entire nonclient left, right, and bottom
// borders, including both the window frame and any client edge.
int NonClientBorderThickness() const;
// Returns the height of the entire nonclient top border, including the window
// frame, any title area, and any connected client edge.
int NonClientTopBorderHeight() const;
// Returns the y-coordinate of the caption buttons.
int CaptionButtonY() const;
// Returns the thickness of the nonclient portion of the 3D edge along the
// bottom of the titlebar.
int TitlebarBottomThickness() const;
// Returns the size of the titlebar icon. This is used even when the icon is
// not shown, e.g. to set the titlebar height.
int IconSize() const;
// Returns the bounds of the titlebar icon (or where the icon would be if
// there was one).
gfx::Rect IconBounds() const;
// Returns true if the title bar, caption buttons, and frame border should be
// drawn. If false, the client view occupies the full area of this view.
bool ShouldShowTitleBarAndBorder() const;
// Returns true if the client edge should be drawn. This is true if
// the window is not maximized.
bool ShouldShowClientEdge() const;
// Paint various sub-components of this view.
void PaintRestoredFrameBorder(gfx::Canvas* canvas);
void PaintMaximizedFrameBorder(gfx::Canvas* canvas);
void PaintTitleBar(gfx::Canvas* canvas);
void PaintRestoredClientEdge(gfx::Canvas* canvas);
// Compute aspects of the frame needed to paint the frame background.
SkColor GetFrameColor() const;
gfx::ImageSkia GetFrameImage() const;
// Performs the layout for the window control buttons based on the
// configuration specified in WindowButtonOrderProvider. The sizing and
// positions of the buttons affects LayoutTitleBar, call this beforehand.
void LayoutWindowControls();
// Calculations depend on the positions of the window controls. Always call
// LayoutWindowControls beforehand.
void LayoutTitleBar();
void LayoutClientView();
// Creates, adds and returns a new window caption button (e.g, minimize,
// maximize, restore).
ImageButton* InitWindowCaptionButton(Button::PressedCallback callback,
int accessibility_string_id,
int normal_image_id,
int hot_image_id,
int pushed_image_id);
// Returns the window caption button for the given FrameButton type, if it
// should be visible. Otherwise NULL.
ImageButton* GetImageButton(views::FrameButton button);
// The bounds of the client view, in this view's coordinates.
gfx::Rect client_view_bounds_;
// The layout rect of the title, if visible.
gfx::Rect title_bounds_;
// Not owned.
const raw_ptr<Widget> frame_;
// The icon of this window. May be NULL.
raw_ptr<ImageButton> window_icon_ = nullptr;
// Window caption buttons.
raw_ptr<ImageButton> minimize_button_;
raw_ptr<ImageButton> maximize_button_;
raw_ptr<ImageButton> restore_button_;
raw_ptr<ImageButton> close_button_;
// Background painter for the window frame.
std::unique_ptr<FrameBackground> frame_background_;
// The horizontal boundaries for the title bar to layout within. Restricted
// by the space used by the leading and trailing buttons.
int minimum_title_bar_x_ = 0;
int maximum_title_bar_x_ = -1;
base::CallbackListSubscription paint_as_active_subscription_ =
frame_->RegisterPaintAsActiveChangedCallback(
base::BindRepeating(&CustomFrameView::SchedulePaint,
base::Unretained(this)));
};
} // namespace views
#endif // UI_VIEWS_WINDOW_CUSTOM_FRAME_VIEW_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/window/custom_frame_view.h | C++ | unknown | 6,073 |
// 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/window/custom_frame_view.h"
#include <utility>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/test/views_test_utils.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/window_button_order_provider.h"
namespace views {
class CustomFrameViewTest : public ViewsTestBase {
public:
CustomFrameViewTest() = default;
CustomFrameViewTest(const CustomFrameViewTest&) = delete;
CustomFrameViewTest& operator=(const CustomFrameViewTest&) = delete;
~CustomFrameViewTest() override = default;
CustomFrameView* custom_frame_view() { return custom_frame_view_; }
Widget* widget() { return widget_; }
// ViewsTestBase:
void SetUp() override;
void TearDown() override;
protected:
const std::vector<views::FrameButton>& leading_buttons() {
return WindowButtonOrderProvider::GetInstance()->leading_buttons();
}
const std::vector<views::FrameButton>& trailing_buttons() {
return WindowButtonOrderProvider::GetInstance()->trailing_buttons();
}
ImageButton* minimize_button() {
return custom_frame_view_->minimize_button_;
}
ImageButton* maximize_button() {
return custom_frame_view_->maximize_button_;
}
ImageButton* restore_button() { return custom_frame_view_->restore_button_; }
ImageButton* close_button() { return custom_frame_view_->close_button_; }
gfx::Rect title_bounds() { return custom_frame_view_->title_bounds_; }
void SetWindowButtonOrder(
const std::vector<views::FrameButton> leading_buttons,
const std::vector<views::FrameButton> trailing_buttons);
private:
std::unique_ptr<WidgetDelegate> widget_delegate_;
// Parent container for |custom_frame_view_|
raw_ptr<Widget> widget_;
// Owned by |widget_|
raw_ptr<CustomFrameView> custom_frame_view_;
};
void CustomFrameViewTest::SetUp() {
ViewsTestBase::SetUp();
widget_ = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
widget_delegate_ = std::make_unique<WidgetDelegate>();
params.delegate = widget_delegate_.get();
params.delegate->SetCanMaximize(true);
params.delegate->SetCanMinimize(true);
params.remove_standard_frame = true;
widget_->Init(std::move(params));
auto custom_frame_view = std::make_unique<CustomFrameView>(widget_);
custom_frame_view_ = custom_frame_view.get();
widget_->non_client_view()->SetFrameView(std::move(custom_frame_view));
}
void CustomFrameViewTest::TearDown() {
widget_->CloseNow();
ViewsTestBase::TearDown();
}
void CustomFrameViewTest::SetWindowButtonOrder(
const std::vector<views::FrameButton> leading_buttons,
const std::vector<views::FrameButton> trailing_buttons) {
WindowButtonOrderProvider::GetInstance()->SetWindowButtonOrder(
leading_buttons, trailing_buttons);
}
// Tests that there is a default button ordering before initialization causes
// a configuration file check.
TEST_F(CustomFrameViewTest, DefaultButtons) {
const std::vector<views::FrameButton>& trailing = trailing_buttons();
EXPECT_EQ(trailing.size(), 3u);
EXPECT_TRUE(leading_buttons().empty());
EXPECT_EQ(trailing[0], views::FrameButton::kMinimize);
EXPECT_EQ(trailing[1], views::FrameButton::kMaximize);
EXPECT_EQ(trailing[2], views::FrameButton::kClose);
}
// Tests that layout places the buttons in order, that the restore button is
// hidden and the buttons are placed after the title.
TEST_F(CustomFrameViewTest, DefaultButtonLayout) {
widget()->SetBounds(gfx::Rect(0, 0, 300, 100));
widget()->Show();
EXPECT_LT(minimize_button()->x(), maximize_button()->x());
EXPECT_LT(maximize_button()->x(), close_button()->x());
EXPECT_FALSE(restore_button()->GetVisible());
EXPECT_GT(minimize_button()->x(),
title_bounds().x() + title_bounds().width());
}
// Tests that setting the buttons to leading places them before the title.
TEST_F(CustomFrameViewTest, LeadingButtonLayout) {
std::vector<views::FrameButton> leading;
leading.push_back(views::FrameButton::kClose);
leading.push_back(views::FrameButton::kMinimize);
leading.push_back(views::FrameButton::kMaximize);
std::vector<views::FrameButton> trailing;
SetWindowButtonOrder(leading, trailing);
widget()->SetBounds(gfx::Rect(0, 0, 300, 100));
widget()->Show();
EXPECT_LT(close_button()->x(), minimize_button()->x());
EXPECT_LT(minimize_button()->x(), maximize_button()->x());
EXPECT_FALSE(restore_button()->GetVisible());
EXPECT_LT(maximize_button()->x() + maximize_button()->width(),
title_bounds().x());
}
// Tests that layouts occurring while maximized swap the maximize button for the
// restore button
TEST_F(CustomFrameViewTest, MaximizeRevealsRestoreButton) {
widget()->SetBounds(gfx::Rect(0, 0, 300, 100));
widget()->Show();
ASSERT_FALSE(restore_button()->GetVisible());
ASSERT_TRUE(maximize_button()->GetVisible());
widget()->Maximize();
// Just calling Maximize() doesn't invlidate the layout immediately.
custom_frame_view()->InvalidateLayout();
views::test::RunScheduledLayout(custom_frame_view());
#if BUILDFLAG(IS_MAC)
// Restore buttons do not exist on Mac. The maximize button is instead a kind
// of toggle, but has no effect on frame decorations.
EXPECT_FALSE(restore_button()->GetVisible());
EXPECT_TRUE(maximize_button()->GetVisible());
#else
EXPECT_TRUE(restore_button()->GetVisible());
EXPECT_FALSE(maximize_button()->GetVisible());
#endif
}
// Tests that when the parent cannot maximize that the maximize button is not
// visible
TEST_F(CustomFrameViewTest, CannotMaximizeHidesButton) {
widget()->widget_delegate()->SetCanMaximize(false);
widget()->SetBounds(gfx::Rect(0, 0, 300, 100));
widget()->Show();
EXPECT_FALSE(restore_button()->GetVisible());
EXPECT_FALSE(maximize_button()->GetVisible());
}
// Tests that when the parent cannot minimize that the minimize button is not
// visible
TEST_F(CustomFrameViewTest, CannotMinimizeHidesButton) {
widget()->widget_delegate()->SetCanMinimize(false);
widget()->SetBounds(gfx::Rect(0, 0, 300, 100));
widget()->Show();
EXPECT_FALSE(minimize_button()->GetVisible());
}
// Tests that when maximized that the edge button has an increased width.
TEST_F(CustomFrameViewTest, LargerEdgeButtonsWhenMaximized) {
// Custom ordering to have a button on each edge.
std::vector<views::FrameButton> leading;
leading.push_back(views::FrameButton::kClose);
leading.push_back(views::FrameButton::kMaximize);
std::vector<views::FrameButton> trailing;
trailing.push_back(views::FrameButton::kMinimize);
SetWindowButtonOrder(leading, trailing);
widget()->SetBounds(gfx::Rect(0, 0, 300, 100));
widget()->Show();
gfx::Rect close_button_initial_bounds = close_button()->bounds();
gfx::Rect minimize_button_initial_bounds = minimize_button()->bounds();
widget()->Maximize();
// Just calling Maximize() doesn't invlidate the layout immediately.
custom_frame_view()->InvalidateLayout();
views::test::RunScheduledLayout(custom_frame_view());
#if BUILDFLAG(IS_MAC)
// On Mac, "Maximize" should not alter the frame. Only fullscreen does that.
EXPECT_EQ(close_button()->bounds().width(),
close_button_initial_bounds.width());
EXPECT_EQ(minimize_button()->bounds().width(),
minimize_button_initial_bounds.width());
#else
EXPECT_GT(close_button()->bounds().width(),
close_button_initial_bounds.width());
EXPECT_GT(minimize_button()->bounds().width(),
minimize_button_initial_bounds.width());
#endif
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/window/custom_frame_view_unittest.cc | C++ | unknown | 7,855 |
// 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/window/dialog_client_view.h"
#include <algorithm>
#include <memory>
#include <utility>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/ranges/algorithm.h"
#include "build/build_config.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/views/background.h"
#include "ui/views/border.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/button/checkbox.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/button/md_text_button.h"
#include "ui/views/layout/layout_provider.h"
#include "ui/views/layout/table_layout.h"
#include "ui/views/metadata/view_factory.h"
#include "ui/views/style/platform_style.h"
#include "ui/views/view_observer.h"
#include "ui/views/view_tracker.h"
#include "ui/views/view_utils.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_delegate.h"
namespace views {
namespace {
// The group used by the buttons. This name is chosen voluntarily big not to
// conflict with other groups that could be in the dialog content.
constexpr int kButtonGroup = 6666;
// Returns true if the given view should be shown (i.e. exists and is
// visible).
bool ShouldShow(View* view) {
return view && view->GetVisible();
}
// Returns the bounding box required to contain |size1| and |size2|, placed one
// atop the other.
gfx::Size GetBoundingSizeForVerticalStack(const gfx::Size& size1,
const gfx::Size& size2) {
return gfx::Size(std::max(size1.width(), size2.width()),
size1.height() + size2.height());
}
} // namespace
// Simple container to bubble child view changes up the view hierarchy.
class DialogClientView::ButtonRowContainer : public View {
public:
METADATA_HEADER(ButtonRowContainer);
explicit ButtonRowContainer(DialogClientView* owner) : owner_(owner) {}
ButtonRowContainer(const ButtonRowContainer&) = delete;
ButtonRowContainer& operator=(const ButtonRowContainer&) = delete;
// View:
void ChildPreferredSizeChanged(View* child) override {
owner_->ChildPreferredSizeChanged(child);
}
void ChildVisibilityChanged(View* child) override {
owner_->ChildVisibilityChanged(child);
}
private:
const raw_ptr<DialogClientView> owner_;
};
BEGIN_METADATA(DialogClientView, ButtonRowContainer, View)
END_METADATA
DialogClientView::DialogClientView(Widget* owner, View* contents_view)
: ClientView(owner, contents_view),
button_row_insets_(
LayoutProvider::Get()->GetInsetsMetric(INSETS_DIALOG_BUTTON_ROW)),
input_protector_(
std::make_unique<views::InputEventActivationProtector>()) {
// Doing this now ensures this accelerator will have lower priority than
// one set by the contents view.
AddAccelerator(ui::Accelerator(ui::VKEY_ESCAPE, ui::EF_NONE));
button_row_container_ =
AddChildView(std::make_unique<ButtonRowContainer>(this));
}
DialogClientView::~DialogClientView() {
DialogDelegate* dialog = GetWidget() ? GetDialogDelegate() : nullptr;
if (dialog)
dialog->RemoveObserver(this);
}
void DialogClientView::SetButtonRowInsets(const gfx::Insets& insets) {
button_row_insets_ = insets;
if (GetWidget())
UpdateDialogButtons();
}
gfx::Size DialogClientView::CalculatePreferredSize() const {
const gfx::Insets& content_margins = GetDialogDelegate()->margins();
gfx::Size contents_size;
const int fixed_width = GetDialogDelegate()->fixed_width();
if (fixed_width) {
const int content_width = fixed_width - content_margins.width();
contents_size = gfx::Size(content_width,
ClientView::GetHeightForWidth(content_width));
} else {
contents_size = ClientView::CalculatePreferredSize();
}
contents_size.Enlarge(content_margins.width(), content_margins.height());
return GetBoundingSizeForVerticalStack(
contents_size, button_row_container_->GetPreferredSize());
}
gfx::Size DialogClientView::GetMinimumSize() const {
// TODO(pbos): Try to find a way for ClientView::GetMinimumSize() to be
// fixed-width aware. For now this uses min-size = preferred size for
// fixed-width dialogs (even though min height might not be preferred height).
// Fixing this might require View::GetMinHeightForWidth().
if (GetDialogDelegate()->fixed_width())
return CalculatePreferredSize();
return GetBoundingSizeForVerticalStack(
ClientView::GetMinimumSize(), button_row_container_->GetMinimumSize());
}
gfx::Size DialogClientView::GetMaximumSize() const {
constexpr int kUnconstrained = 0;
DCHECK(gfx::Size(kUnconstrained, kUnconstrained) ==
button_row_container_->GetMaximumSize());
gfx::Size max_size = ClientView::GetMaximumSize();
// If the height is constrained, add the button row height. Leave the width as
// it is (be it constrained or unconstrained).
if (max_size.height() != kUnconstrained)
max_size.Enlarge(0, button_row_container_->GetPreferredSize().height());
// Note not all constraints can be met. E.g. it's possible here for
// GetMinimumSize().width() to be larger than max_size.width() since the
// former includes the button row width, but the latter does not. It is up to
// the DialogDelegate to ensure its maximum size is reasonable for the buttons
// it wants, or leave it unconstrained.
return max_size;
}
void DialogClientView::VisibilityChanged(View* starting_from, bool is_visible) {
ClientView::VisibilityChanged(starting_from, is_visible);
input_protector_->VisibilityChanged(is_visible);
}
void DialogClientView::Layout() {
button_row_container_->SetSize(
gfx::Size(width(), button_row_container_->GetHeightForWidth(width())));
button_row_container_->SetY(height() - button_row_container_->height());
if (contents_view()) {
gfx::Rect contents_bounds(width(), button_row_container_->y());
contents_bounds.Inset(GetDialogDelegate()->margins());
contents_view()->SetBoundsRect(contents_bounds);
}
}
bool DialogClientView::AcceleratorPressed(const ui::Accelerator& accelerator) {
DCHECK_EQ(accelerator.key_code(), ui::VKEY_ESCAPE);
// If there's no close-x (typically the case for modal dialogs) then Cancel
// the dialog instead of closing the widget as the delegate may likely expect
// either Accept or Cancel to be called as a result of user action.
DialogDelegate* const delegate = GetDialogDelegate();
if (delegate && delegate->EscShouldCancelDialog()) {
delegate->CancelDialog();
return true;
}
GetWidget()->CloseWithReason(Widget::ClosedReason::kEscKeyPressed);
return true;
}
void DialogClientView::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
View* const child = details.child;
ClientView::ViewHierarchyChanged(details);
if (details.is_add) {
if (child == this) {
UpdateDialogButtons();
GetDialogDelegate()->AddObserver(this);
}
return;
}
if (details.parent != button_row_container_)
return;
// SetupViews() adds/removes children, and manages their position.
if (adding_or_removing_views_)
return;
if (child == ok_button_)
ok_button_ = nullptr;
else if (child == cancel_button_)
cancel_button_ = nullptr;
else if (child == extra_view_)
extra_view_ = nullptr;
}
void DialogClientView::OnThemeChanged() {
ClientView::OnThemeChanged();
// The old dialog style needs an explicit background color, while the new
// dialog style simply inherits the bubble's frame view color.
const DialogDelegate* dialog = GetDialogDelegate();
if (dialog && !dialog->use_custom_frame()) {
SetBackground(views::CreateSolidBackground(
GetColorProvider()->GetColor(ui::kColorDialogBackground)));
}
}
void DialogClientView::UpdateInputProtectorTimeStamp() {
input_protector_->UpdateViewShownTimeStamp();
}
void DialogClientView::ResetViewShownTimeStampForTesting() {
input_protector_->ResetForTesting(); // IN-TEST
}
DialogDelegate* DialogClientView::GetDialogDelegate() const {
return GetWidget()->widget_delegate()->AsDialogDelegate();
}
void DialogClientView::ChildVisibilityChanged(View* child) {
// Showing or hiding |extra_view_| can alter which columns have linked sizes.
if (child == extra_view_)
UpdateDialogButtons();
InvalidateLayout();
}
void DialogClientView::TriggerInputProtection() {
input_protector_->UpdateViewShownTimeStamp();
}
void DialogClientView::OnDialogChanged() {
UpdateDialogButtons();
}
void DialogClientView::UpdateDialogButtons() {
SetupLayout();
InvalidateLayout();
}
void DialogClientView::UpdateDialogButton(LabelButton** member,
ui::DialogButton type) {
DialogDelegate* const delegate = GetDialogDelegate();
if (!(delegate->GetDialogButtons() & type)) {
if (*member)
button_row_container_->RemoveChildViewT(*member);
*member = nullptr;
return;
}
const bool is_default = delegate->GetDefaultDialogButton() == type &&
(type != ui::DIALOG_BUTTON_CANCEL ||
PlatformStyle::kDialogDefaultButtonCanBeCancel);
const std::u16string title = delegate->GetDialogButtonLabel(type);
if (*member) {
LabelButton* button = *member;
button->SetEnabled(delegate->IsDialogButtonEnabled(type));
button->SetIsDefault(is_default);
button->SetText(title);
return;
}
const int minimum_width = LayoutProvider::Get()->GetDistanceMetric(
views::DISTANCE_DIALOG_BUTTON_MINIMUM_WIDTH);
Builder<View>(button_row_container_)
.AddChild(
Builder<MdTextButton>()
.CopyAddressTo(member)
.SetCallback(base::BindRepeating(&DialogClientView::ButtonPressed,
base::Unretained(this), type))
.SetText(title)
.SetProminent(is_default)
.SetIsDefault(is_default)
.SetEnabled(delegate->IsDialogButtonEnabled(type))
.SetMinSize(gfx::Size(minimum_width, 0))
.SetGroup(kButtonGroup))
.BuildChildren();
}
void DialogClientView::ButtonPressed(ui::DialogButton type,
const ui::Event& event) {
DialogDelegate* const delegate = GetDialogDelegate();
if (delegate && !input_protector_->IsPossiblyUnintendedInteraction(event)) {
(type == ui::DIALOG_BUTTON_OK) ? delegate->AcceptDialog()
: delegate->CancelDialog();
}
}
int DialogClientView::GetExtraViewSpacing() const {
if (!ShouldShow(extra_view_) || !(ok_button_ || cancel_button_))
return 0;
return LayoutProvider::Get()->GetDistanceMetric(
views::DISTANCE_RELATED_BUTTON_HORIZONTAL);
}
std::array<View*, DialogClientView::kNumButtons>
DialogClientView::GetButtonRowViews() {
View* first = ShouldShow(extra_view_) ? extra_view_.get() : nullptr;
View* second = cancel_button_;
View* third = ok_button_;
if (cancel_button_ && (PlatformStyle::kIsOkButtonLeading == !!ok_button_))
std::swap(second, third);
return {{first, second, third}};
}
void DialogClientView::SetupLayout() {
base::AutoReset<bool> auto_reset(&adding_or_removing_views_, true);
FocusManager* focus_manager = GetFocusManager();
ViewTracker view_tracker(focus_manager->GetFocusedView());
// Clobber the layout manager in case there are no views in which to layout.
button_row_container_->SetLayoutManager(nullptr);
SetupViews();
const std::array<View*, kNumButtons> views = GetButtonRowViews();
// Visibility changes on |extra_view_| must be observed to re-Layout. However,
// when hidden it's not included in the button row (it can't influence layout)
// and it can't be added to |button_row_container_|. So add it, hidden, to
// |this| so it can be observed.
if (extra_view_) {
if (!views[0])
AddChildView(extra_view_.get());
else if (views[0])
button_row_container_->AddChildViewAt(extra_view_.get(), 0);
}
if (base::ranges::count(views, nullptr) == kNumButtons)
return;
// This will also clobber any existing layout manager and clear any settings
// it may already have.
auto* layout = button_row_container_->SetLayoutManager(
std::make_unique<views::TableLayout>());
layout->SetMinimumSize(minimum_size_);
// The |resize_percent| constants. There's only one stretchy column (padding
// to the left of ok/cancel buttons).
constexpr float kFixed = views::TableLayout::kFixedSize;
constexpr float kStretchy = 1.0f;
// Button row is [ extra <pad+stretchy> second <pad> third ]. Ensure the
// <pad> column is zero width if there isn't a button on either side.
// GetExtraViewSpacing() handles <pad+stretchy>.
LayoutProvider* const layout_provider = LayoutProvider::Get();
const int button_spacing = (ok_button_ && cancel_button_)
? layout_provider->GetDistanceMetric(
DISTANCE_RELATED_BUTTON_HORIZONTAL)
: 0;
// Rather than giving |button_row_container_| a Border, incorporate the
// insets into the layout. This simplifies min/max size calculations.
layout->SetMinimumSize(minimum_size_)
.AddPaddingColumn(kFixed, button_row_insets_.left())
.AddColumn(LayoutAlignment::kStretch, LayoutAlignment::kStretch, kFixed,
TableLayout::ColumnSize::kUsePreferred, 0, 0)
.AddPaddingColumn(kStretchy, GetExtraViewSpacing())
.AddColumn(LayoutAlignment::kStretch, LayoutAlignment::kEnd, kFixed,
TableLayout::ColumnSize::kUsePreferred, 0, 0)
.AddPaddingColumn(kFixed, button_spacing)
.AddColumn(LayoutAlignment::kStretch, LayoutAlignment::kEnd, kFixed,
TableLayout::ColumnSize::kUsePreferred, 0, 0)
.AddPaddingColumn(kFixed, button_row_insets_.right())
.AddPaddingRow(kFixed, button_row_insets_.top())
.AddRows(1, kFixed)
.AddPaddingRow(kFixed, button_row_insets_.bottom())
.SetLinkedColumnSizeLimit(layout_provider->GetDistanceMetric(
DISTANCE_BUTTON_MAX_LINKABLE_WIDTH));
// Track which columns to link sizes under MD.
constexpr size_t kViewToColumnIndex[] = {1, 3, 5};
std::vector<size_t> columns_to_link;
// Skip views that are not a button, or are a specific subclass of Button
// that should never be linked. Otherwise, link everything.
auto should_link = [](views::View* view) {
return IsViewClass<Button>(view) && !IsViewClass<Checkbox>(view) &&
!IsViewClass<ImageButton>(view);
};
for (size_t view_index = 0; view_index < kNumButtons; ++view_index) {
if (views[view_index]) {
RemoveFillerView(view_index);
button_row_container_->ReorderChildView(views[view_index], view_index);
if (should_link(views[view_index]))
columns_to_link.push_back(kViewToColumnIndex[view_index]);
} else {
AddFillerView(view_index);
}
}
layout->LinkColumnSizes(columns_to_link);
// The default focus is lost when child views are added back into the dialog.
// This restores focus if the button is still available.
View* previously_focused_view = view_tracker.view();
if (previously_focused_view && !focus_manager->GetFocusedView() &&
Contains(previously_focused_view)) {
previously_focused_view->RequestFocus();
}
}
void DialogClientView::SetupViews() {
if (PlatformStyle::kIsOkButtonLeading) {
UpdateDialogButton(&ok_button_, ui::DIALOG_BUTTON_OK);
UpdateDialogButton(&cancel_button_, ui::DIALOG_BUTTON_CANCEL);
} else {
UpdateDialogButton(&cancel_button_, ui::DIALOG_BUTTON_CANCEL);
UpdateDialogButton(&ok_button_, ui::DIALOG_BUTTON_OK);
}
auto disowned_extra_view = GetDialogDelegate()->DisownExtraView();
if (!disowned_extra_view)
return;
delete extra_view_;
extra_view_ = disowned_extra_view.release();
if (extra_view_ && IsViewClass<Button>(extra_view_))
extra_view_->SetGroup(kButtonGroup);
}
void DialogClientView::AddFillerView(size_t view_index) {
DCHECK_LT(view_index, kNumButtons);
View*& filler = filler_views_[view_index];
if (!filler) {
filler = button_row_container_->AddChildViewAt(
std::make_unique<View>(),
std::min(button_row_container_->children().size(), view_index));
}
}
void DialogClientView::RemoveFillerView(size_t view_index) {
DCHECK_LT(view_index, kNumButtons);
View*& filler = filler_views_[view_index];
if (filler) {
button_row_container_->RemoveChildViewT(filler);
filler = nullptr;
}
}
BEGIN_METADATA(DialogClientView, ClientView)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/window/dialog_client_view.cc | C++ | unknown | 16,961 |
// 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_WINDOW_DIALOG_CLIENT_VIEW_H_
#define UI_VIEWS_WINDOW_DIALOG_CLIENT_VIEW_H_
#include <memory>
#include <utility>
#include "base/gtest_prod_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "ui/base/ui_base_types.h"
#include "ui/views/input_event_activation_protector.h"
#include "ui/views/metadata/view_factory.h"
#include "ui/views/window/client_view.h"
#include "ui/views/window/dialog_observer.h"
namespace views {
class DialogDelegate;
class LabelButton;
class Widget;
// DialogClientView provides adornments for a dialog's content view, including
// custom-labeled [OK] and [Cancel] buttons with [Enter] and [Esc] accelerators.
// The view also displays the delegate's extra view alongside the buttons. The
// view appears like below. NOTE: The contents view is not inset on the top or
// side client view edges.
// +------------------------------+
// | Contents View |
// +------------------------------+
// | [Extra View] [OK] [Cancel] |
// +------------------------------+
//
// You must not directly depend on or use DialogClientView; it is internal to
// //ui/views. Access it through the public interfaces on DialogDelegate. It is
// only VIEWS_EXPORT to make it available to views_unittests.
class VIEWS_EXPORT DialogClientView : public ClientView, public DialogObserver {
public:
METADATA_HEADER(DialogClientView);
DialogClientView(Widget* widget, View* contents_view);
DialogClientView(const DialogClientView&) = delete;
DialogClientView& operator=(const DialogClientView&) = delete;
~DialogClientView() override;
// Accessors in case the user wishes to adjust these buttons.
LabelButton* ok_button() const { return ok_button_; }
LabelButton* cancel_button() const { return cancel_button_; }
View* extra_view() const { return extra_view_; }
void SetButtonRowInsets(const gfx::Insets& insets);
// View implementation:
gfx::Size CalculatePreferredSize() const override;
gfx::Size GetMinimumSize() const override;
gfx::Size GetMaximumSize() const override;
void VisibilityChanged(View* starting_from, bool is_visible) override;
// Input protection is triggered upon prompt creation and updated on
// visibility changes. Other situations such as top window changes in certain
// situations should trigger the input protection manually by calling this
// method. Input protection protects against certain kinds of clickjacking.
// Essentially it prevents clicks that happen within a user's double click
// interval from when the protection is started as well as any following
// clicks that happen in shorter succession than the user's double click
// interval. Refer to InputEventActivationProtector for more information.
void TriggerInputProtection();
void Layout() override;
bool AcceleratorPressed(const ui::Accelerator& accelerator) override;
void ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) override;
void OnThemeChanged() override;
// Update the |view_shown_time_stamp_| of input protector. A short time
// from this point onward, input event will be ignored.
void UpdateInputProtectorTimeStamp();
void set_minimum_size(const gfx::Size& size) { minimum_size_ = size; }
// Resets the time when view has been shown. Tests may need to call this
// method if they use events that could be otherwise treated as unintended.
// See IsPossiblyUnintendedInteraction().
void ResetViewShownTimeStampForTesting();
// Override the internal input protector for testing; usually to inject a mock
// version whose return value can be controlled.
void SetInputProtectorForTesting(
std::unique_ptr<views::InputEventActivationProtector> input_protector) {
input_protector_ = std::move(input_protector);
}
private:
enum {
// The number of buttons that DialogClientView can support.
kNumButtons = 3
};
class ButtonRowContainer;
// Returns the DialogDelegate for the window.
DialogDelegate* GetDialogDelegate() const;
// View implementation.
void ChildVisibilityChanged(View* child) override;
// DialogObserver:
void OnDialogChanged() override;
// Update the dialog buttons to match the dialog's delegate.
void UpdateDialogButtons();
// Creates, deletes, or updates the appearance of the button of type |type|
// (which must be pointed to by |member|). Which action is chosen is based on
// whether DialogDelegate::GetDialogButtons() includes |type|, and whether
// |member| points to a button that already exists.
void UpdateDialogButton(LabelButton** member, ui::DialogButton type);
void ButtonPressed(ui::DialogButton type, const ui::Event& event);
// Returns the spacing between the extra view and the ok/cancel buttons. 0 if
// no extra view. Otherwise uses the default padding.
int GetExtraViewSpacing() const;
// Returns Views in the button row, as they should appear in the layout. If
// a View should not appear, it will be null.
std::array<View*, kNumButtons> GetButtonRowViews();
// Installs and configures the LayoutManager for |button_row_container_|.
void SetupLayout();
// Creates or deletes any buttons that are required. Updates data members.
// After calling this, no button row Views will be in the view hierarchy.
void SetupViews();
// Adds/Removes a filler view depending on whether the corresponding live view
// is present.
void AddFillerView(size_t view_index);
void RemoveFillerView(size_t view_index);
// How much to inset the button row.
gfx::Insets button_row_insets_;
// The minimum size of this dialog, regardless of the size of its content
// view.
gfx::Size minimum_size_;
// The dialog buttons.
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION LabelButton* ok_button_ = nullptr;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION LabelButton* cancel_button_ = nullptr;
// The extra view shown in the row of buttons; may be NULL.
raw_ptr<View, DanglingUntriaged> extra_view_ = nullptr;
// Container view for the button row.
raw_ptr<ButtonRowContainer> button_row_container_ = nullptr;
// List of "filler" views used to keep columns in sync for TableLayout.
std::array<View*, kNumButtons> filler_views_ = {nullptr, nullptr, nullptr};
// Used to prevent unnecessary or potentially harmful changes during
// SetupLayout(). Everything will be manually updated afterwards.
bool adding_or_removing_views_ = false;
std::unique_ptr<InputEventActivationProtector> input_protector_;
};
BEGIN_VIEW_BUILDER(VIEWS_EXPORT, DialogClientView, ClientView)
END_VIEW_BUILDER
} // namespace views
DEFINE_VIEW_BUILDER(VIEWS_EXPORT, DialogClientView)
#endif // UI_VIEWS_WINDOW_DIALOG_CLIENT_VIEW_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/window/dialog_client_view.h | C++ | unknown | 7,029 |
// 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/window/dialog_client_view.h"
#include <algorithm>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "ui/base/ui_base_types.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/event.h"
#include "ui/events/event_constants.h"
#include "ui/events/gesture_event_details.h"
#include "ui/events/pointer_details.h"
#include "ui/events/types/event_type.h"
#include "ui/gfx/geometry/point.h"
#include "ui/views/controls/button/checkbox.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/metrics.h"
#include "ui/views/style/platform_style.h"
#include "ui/views/test/button_test_api.h"
#include "ui/views/test/test_layout_provider.h"
#include "ui/views/test/test_views.h"
#include "ui/views/test/views_test_utils.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_delegate.h"
namespace views {
// Base class for tests. Also acts as the dialog delegate and contents view for
// TestDialogClientView.
class DialogClientViewTest : public test::WidgetTest {
public:
DialogClientViewTest() = default;
DialogClientViewTest(const DialogClientViewTest&) = delete;
DialogClientViewTest& operator=(const DialogClientViewTest&) = delete;
// testing::Test:
void SetUp() override {
WidgetTest::SetUp();
delegate_ = new TestDialogDelegateView(this);
delegate_->set_use_custom_frame(false);
delegate_->SetButtons(ui::DIALOG_BUTTON_NONE);
// Note: not using DialogDelegate::CreateDialogWidget(..), since that can
// alter the frame type according to the platform.
widget_ = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.delegate = delegate_;
widget_->Init(std::move(params));
layout_provider_ = std::make_unique<test::TestLayoutProvider>();
layout_provider_->SetDistanceMetric(DISTANCE_BUTTON_MAX_LINKABLE_WIDTH,
200);
}
void TearDown() override {
widget_->CloseNow();
WidgetTest::TearDown();
}
protected:
gfx::Rect GetUpdatedClientBounds() {
SizeAndLayoutWidget();
return client_view()->bounds();
}
void SizeAndLayoutWidget() {
Widget* dialog = widget();
dialog->SetSize(dialog->GetContentsView()->GetPreferredSize());
views::test::RunScheduledLayout(dialog);
}
// Makes sure that the content view is sized correctly. Width must be at least
// the requested amount, but height should always match exactly.
void CheckContentsIsSetToPreferredSize() {
const gfx::Rect client_bounds = GetUpdatedClientBounds();
const gfx::Size preferred_size = delegate_->GetPreferredSize();
EXPECT_EQ(preferred_size.height(), delegate_->bounds().height());
EXPECT_LE(preferred_size.width(), delegate_->bounds().width());
EXPECT_EQ(gfx::Point(), delegate_->origin());
EXPECT_EQ(client_bounds.width(), delegate_->width());
}
// Sets the buttons to show in the dialog and refreshes the dialog.
void SetDialogButtons(int dialog_buttons) {
delegate_->SetButtons(dialog_buttons);
delegate_->DialogModelChanged();
}
void SetDialogButtonLabel(ui::DialogButton button,
const std::u16string& label) {
delegate_->SetButtonLabel(button, label);
delegate_->DialogModelChanged();
}
// Sets the view to provide to DisownExtraView() and updates the dialog. This
// can only be called a single time because DialogClientView caches the result
// of DisownExtraView() and never calls it again.
template <typename T>
T* SetExtraView(std::unique_ptr<T> view) {
T* passed_view = delegate_->SetExtraView(std::move(view));
delegate_->DialogModelChanged();
return passed_view;
}
void SetSizeConstraints(const gfx::Size& min_size,
const gfx::Size& preferred_size,
const gfx::Size& max_size) {
min_size_ = min_size;
preferred_size_ = preferred_size;
max_size_ = max_size;
}
View* FocusableViewAfter(View* view) {
const bool dont_loop = false;
const bool reverse = false;
return delegate_->GetFocusManager()->GetNextFocusableView(
view, delegate_->GetWidget(), reverse, dont_loop);
}
// Set a longer than normal Cancel label so that the minimum button width is
// exceeded. The resulting width is around 160 pixels, but depends on system
// fonts.
void SetLongCancelLabel() {
delegate_->SetButtonLabel(ui::DIALOG_BUTTON_CANCEL,
u"Cancel Cancel Cancel");
delegate_->DialogModelChanged();
}
Button* GetButtonByAccessibleName(View* root, const std::u16string& name) {
Button* button = Button::AsButton(root);
if (button && button->GetAccessibleName() == name)
return button;
for (auto* child : root->children()) {
button = GetButtonByAccessibleName(child, name);
if (button)
return button;
}
return nullptr;
}
Button* GetButtonByAccessibleName(const std::u16string& name) {
return GetButtonByAccessibleName(widget_->GetRootView(), name);
}
DialogClientView* client_view() {
return static_cast<DialogClientView*>(widget_->client_view());
}
DialogDelegateView* delegate() { return delegate_; }
Widget* widget() { return widget_; }
test::TestLayoutProvider* layout_provider() { return layout_provider_.get(); }
private:
class TestDialogDelegateView : public DialogDelegateView {
public:
explicit TestDialogDelegateView(DialogClientViewTest* parent)
: parent_(parent) {}
// DialogDelegateView:
gfx::Size CalculatePreferredSize() const override {
return parent_->preferred_size_;
}
gfx::Size GetMinimumSize() const override { return parent_->min_size_; }
gfx::Size GetMaximumSize() const override { return parent_->max_size_; }
private:
const raw_ptr<DialogClientViewTest> parent_;
};
// The dialog Widget.
std::unique_ptr<test::TestLayoutProvider> layout_provider_;
raw_ptr<Widget> widget_ = nullptr;
raw_ptr<DialogDelegateView> delegate_ = nullptr;
gfx::Size preferred_size_;
gfx::Size min_size_;
gfx::Size max_size_;
};
TEST_F(DialogClientViewTest, UpdateButtons) {
// Make sure this test runs on all platforms. Mac doesn't allow 0 size
// windows. Test only makes sure the size changes based on whether the buttons
// exist or not. The initial size should not matter.
SetSizeConstraints(gfx::Size(200, 100), gfx::Size(300, 200),
gfx::Size(400, 300));
// This dialog should start with no buttons.
EXPECT_EQ(delegate()->GetDialogButtons(), ui::DIALOG_BUTTON_NONE);
EXPECT_EQ(nullptr, client_view()->ok_button());
EXPECT_EQ(nullptr, client_view()->cancel_button());
const int height_without_buttons = GetUpdatedClientBounds().height();
// Update to use both buttons.
SetDialogButtons(ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL);
EXPECT_TRUE(client_view()->ok_button()->GetIsDefault());
EXPECT_FALSE(client_view()->cancel_button()->GetIsDefault());
const int height_with_buttons = GetUpdatedClientBounds().height();
EXPECT_GT(height_with_buttons, height_without_buttons);
// Remove the dialog buttons.
SetDialogButtons(ui::DIALOG_BUTTON_NONE);
EXPECT_EQ(nullptr, client_view()->ok_button());
EXPECT_EQ(nullptr, client_view()->cancel_button());
EXPECT_EQ(GetUpdatedClientBounds().height(), height_without_buttons);
// Reset with just an ok button.
SetDialogButtons(ui::DIALOG_BUTTON_OK);
EXPECT_TRUE(client_view()->ok_button()->GetIsDefault());
EXPECT_EQ(nullptr, client_view()->cancel_button());
EXPECT_EQ(GetUpdatedClientBounds().height(), height_with_buttons);
// Reset with just a cancel button.
SetDialogButtons(ui::DIALOG_BUTTON_CANCEL);
EXPECT_EQ(nullptr, client_view()->ok_button());
EXPECT_EQ(client_view()->cancel_button()->GetIsDefault(),
PlatformStyle::kDialogDefaultButtonCanBeCancel);
EXPECT_EQ(GetUpdatedClientBounds().height(), height_with_buttons);
}
TEST_F(DialogClientViewTest, RemoveAndUpdateButtons) {
// Removing buttons from another context should clear the local pointer.
SetDialogButtons(ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL);
delete client_view()->ok_button();
EXPECT_EQ(nullptr, client_view()->ok_button());
delete client_view()->cancel_button();
EXPECT_EQ(nullptr, client_view()->cancel_button());
// Updating should restore the requested buttons properly.
SetDialogButtons(ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL);
EXPECT_TRUE(client_view()->ok_button()->GetIsDefault());
EXPECT_FALSE(client_view()->cancel_button()->GetIsDefault());
}
// Test that views inside the dialog client view have the correct focus order.
TEST_F(DialogClientViewTest, SetupFocusChain) {
const bool kIsOkButtonOnLeftSide = PlatformStyle::kIsOkButtonLeading;
delegate()->GetContentsView()->SetFocusBehavior(View::FocusBehavior::ALWAYS);
// Initially the dialog client view only contains the content view.
EXPECT_EQ(delegate()->GetContentsView(),
FocusableViewAfter(delegate()->GetContentsView()));
// Add OK and cancel buttons.
SetDialogButtons(ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL);
if (kIsOkButtonOnLeftSide) {
EXPECT_EQ(client_view()->ok_button(),
FocusableViewAfter(delegate()->GetContentsView()));
EXPECT_EQ(client_view()->cancel_button(),
FocusableViewAfter(client_view()->ok_button()));
EXPECT_EQ(delegate()->GetContentsView(),
FocusableViewAfter(client_view()->cancel_button()));
} else {
EXPECT_EQ(client_view()->cancel_button(),
FocusableViewAfter(delegate()->GetContentsView()));
EXPECT_EQ(client_view()->ok_button(),
FocusableViewAfter(client_view()->cancel_button()));
EXPECT_EQ(delegate()->GetContentsView(),
FocusableViewAfter(client_view()->ok_button()));
}
// Add extra view and remove OK button.
View* extra_view =
SetExtraView(std::make_unique<StaticSizedView>(gfx::Size(200, 200)));
extra_view->SetFocusBehavior(View::FocusBehavior::ALWAYS);
SetDialogButtons(ui::DIALOG_BUTTON_CANCEL);
EXPECT_EQ(extra_view, FocusableViewAfter(delegate()->GetContentsView()));
EXPECT_EQ(client_view()->cancel_button(), FocusableViewAfter(extra_view));
EXPECT_EQ(delegate()->GetContentsView(), FocusableViewAfter(client_view()));
// Add a dummy view to the contents view. Consult the FocusManager for the
// traversal order since it now spans different levels of the view hierarchy.
View* dummy_view = new StaticSizedView(gfx::Size(200, 200));
dummy_view->SetFocusBehavior(View::FocusBehavior::ALWAYS);
delegate()->GetContentsView()->SetFocusBehavior(View::FocusBehavior::NEVER);
delegate()->GetContentsView()->AddChildView(dummy_view);
EXPECT_EQ(dummy_view, FocusableViewAfter(client_view()->cancel_button()));
EXPECT_EQ(extra_view, FocusableViewAfter(dummy_view));
EXPECT_EQ(client_view()->cancel_button(), FocusableViewAfter(extra_view));
// Views are added to the contents view, not the client view, so the focus
// chain within the client view is not affected.
// NOTE: The TableLayout requires a view to be in every cell. "Dummy" non-
// focusable views are inserted to satisfy this requirement.
EXPECT_TRUE(!client_view()->cancel_button()->GetNextFocusableView() ||
client_view()
->cancel_button()
->GetNextFocusableView()
->GetFocusBehavior() == View::FocusBehavior::NEVER);
}
// Test that the contents view gets its preferred size in the basic dialog
// configuration.
TEST_F(DialogClientViewTest, ContentsSize) {
// On Mac the size cannot be 0, so we give it a preferred size.
SetSizeConstraints(gfx::Size(200, 100), gfx::Size(300, 200),
gfx::Size(400, 300));
CheckContentsIsSetToPreferredSize();
EXPECT_EQ(delegate()->GetContentsView()->size(), client_view()->size());
EXPECT_EQ(gfx::Size(300, 200), client_view()->size());
}
// Test the effect of the button strip on layout.
TEST_F(DialogClientViewTest, LayoutWithButtons) {
SetDialogButtons(ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL);
CheckContentsIsSetToPreferredSize();
EXPECT_LT(delegate()->GetContentsView()->bounds().bottom(),
client_view()->bounds().bottom());
const gfx::Size no_extra_view_size = client_view()->bounds().size();
View* extra_view =
SetExtraView(std::make_unique<StaticSizedView>(gfx::Size(200, 200)));
CheckContentsIsSetToPreferredSize();
EXPECT_GT(client_view()->bounds().height(), no_extra_view_size.height());
// The dialog is bigger with the extra view than without it.
const gfx::Size with_extra_view_size = client_view()->size();
EXPECT_NE(no_extra_view_size, with_extra_view_size);
// Hiding the extra view removes it.
extra_view->SetVisible(false);
CheckContentsIsSetToPreferredSize();
EXPECT_EQ(no_extra_view_size, client_view()->size());
// Making it visible again adds it back.
extra_view->SetVisible(true);
CheckContentsIsSetToPreferredSize();
EXPECT_EQ(with_extra_view_size, client_view()->size());
// Leave |extra_view| hidden. It should still have a parent, to ensure it is
// owned by a View hierarchy and gets deleted.
extra_view->SetVisible(false);
EXPECT_TRUE(extra_view->parent());
}
// Ensure the minimum, maximum and preferred sizes of the contents view are
// respected by the client view, and that the client view includes the button
// row in its minimum and preferred size calculations.
TEST_F(DialogClientViewTest, MinMaxPreferredSize) {
SetDialogButtons(ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL);
const gfx::Size buttons_size = client_view()->GetPreferredSize();
EXPECT_FALSE(buttons_size.IsEmpty());
// When the contents view has no preference, just fit the buttons. The
// maximum size should be unconstrained in both directions.
EXPECT_EQ(buttons_size, client_view()->GetMinimumSize());
EXPECT_EQ(gfx::Size(), client_view()->GetMaximumSize());
// Ensure buttons are between these widths, for the constants below.
EXPECT_LT(20, buttons_size.width());
EXPECT_GT(300, buttons_size.width());
// With no buttons, client view should match the contents view.
SetDialogButtons(ui::DIALOG_BUTTON_NONE);
SetSizeConstraints(gfx::Size(10, 15), gfx::Size(20, 25), gfx::Size(300, 350));
EXPECT_EQ(gfx::Size(10, 15), client_view()->GetMinimumSize());
EXPECT_EQ(gfx::Size(20, 25), client_view()->GetPreferredSize());
EXPECT_EQ(gfx::Size(300, 350), client_view()->GetMaximumSize());
// With buttons, size should increase vertically only.
SetDialogButtons(ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL);
EXPECT_EQ(gfx::Size(buttons_size.width(), 15 + buttons_size.height()),
client_view()->GetMinimumSize());
EXPECT_EQ(gfx::Size(buttons_size.width(), 25 + buttons_size.height()),
client_view()->GetPreferredSize());
EXPECT_EQ(gfx::Size(300, 350 + buttons_size.height()),
client_view()->GetMaximumSize());
// If the contents view gets bigger, it should take over the width.
SetSizeConstraints(gfx::Size(400, 450), gfx::Size(500, 550),
gfx::Size(600, 650));
EXPECT_EQ(gfx::Size(400, 450 + buttons_size.height()),
client_view()->GetMinimumSize());
EXPECT_EQ(gfx::Size(500, 550 + buttons_size.height()),
client_view()->GetPreferredSize());
EXPECT_EQ(gfx::Size(600, 650 + buttons_size.height()),
client_view()->GetMaximumSize());
}
// Ensure button widths are linked under MD.
TEST_F(DialogClientViewTest, LinkedWidthDoesLink) {
SetLongCancelLabel();
// Ensure there is no default button since getting a bold font can throw off
// the cached sizes.
delegate()->SetDefaultButton(ui::DIALOG_BUTTON_NONE);
SetDialogButtons(ui::DIALOG_BUTTON_OK);
CheckContentsIsSetToPreferredSize();
const int ok_button_only_width = client_view()->ok_button()->width();
SetDialogButtons(ui::DIALOG_BUTTON_CANCEL);
CheckContentsIsSetToPreferredSize();
const int cancel_button_width = client_view()->cancel_button()->width();
EXPECT_LT(cancel_button_width, 200);
// Ensure the single buttons have different preferred widths when alone, and
// that the Cancel button is bigger (so that it dominates the size).
EXPECT_GT(cancel_button_width, ok_button_only_width);
SetDialogButtons(ui::DIALOG_BUTTON_CANCEL | ui::DIALOG_BUTTON_OK);
CheckContentsIsSetToPreferredSize();
// Cancel button shouldn't have changed widths.
EXPECT_EQ(cancel_button_width, client_view()->cancel_button()->width());
// OK button should now match the bigger, cancel button.
EXPECT_EQ(cancel_button_width, client_view()->ok_button()->width());
// But not when the size of the cancel button exceeds the max linkable width.
layout_provider()->SetDistanceMetric(DISTANCE_BUTTON_MAX_LINKABLE_WIDTH, 100);
EXPECT_GT(cancel_button_width, 100);
delegate()->DialogModelChanged();
CheckContentsIsSetToPreferredSize();
EXPECT_EQ(ok_button_only_width, client_view()->ok_button()->width());
layout_provider()->SetDistanceMetric(DISTANCE_BUTTON_MAX_LINKABLE_WIDTH, 200);
// The extra view should also match, if it's a matching button type.
View* extra_button = SetExtraView(std::make_unique<LabelButton>(
Button::PressedCallback(), std::u16string()));
CheckContentsIsSetToPreferredSize();
EXPECT_EQ(cancel_button_width, extra_button->width());
}
TEST_F(DialogClientViewTest, LinkedWidthDoesntLink) {
SetLongCancelLabel();
// Ensure there is no default button since getting a bold font can throw off
// the cached sizes.
delegate()->SetDefaultButton(ui::DIALOG_BUTTON_NONE);
SetDialogButtons(ui::DIALOG_BUTTON_OK);
CheckContentsIsSetToPreferredSize();
const int ok_button_only_width = client_view()->ok_button()->width();
SetDialogButtons(ui::DIALOG_BUTTON_CANCEL);
CheckContentsIsSetToPreferredSize();
const int cancel_button_width = client_view()->cancel_button()->width();
EXPECT_LT(cancel_button_width, 200);
// Ensure the single buttons have different preferred widths when alone, and
// that the Cancel button is bigger (so that it dominates the size).
EXPECT_GT(cancel_button_width, ok_button_only_width);
SetDialogButtons(ui::DIALOG_BUTTON_CANCEL | ui::DIALOG_BUTTON_OK);
CheckContentsIsSetToPreferredSize();
// Cancel button shouldn't have changed widths.
EXPECT_EQ(cancel_button_width, client_view()->cancel_button()->width());
// OK button should now match the bigger, cancel button.
EXPECT_EQ(cancel_button_width, client_view()->ok_button()->width());
// But not when the size of the cancel button exceeds the max linkable width.
layout_provider()->SetDistanceMetric(DISTANCE_BUTTON_MAX_LINKABLE_WIDTH, 100);
EXPECT_GT(cancel_button_width, 100);
delegate()->DialogModelChanged();
CheckContentsIsSetToPreferredSize();
EXPECT_EQ(ok_button_only_width, client_view()->ok_button()->width());
layout_provider()->SetDistanceMetric(DISTANCE_BUTTON_MAX_LINKABLE_WIDTH, 200);
// Checkbox extends LabelButton, but it should not participate in linking.
View* extra_button =
SetExtraView(std::make_unique<Checkbox>(std::u16string()));
CheckContentsIsSetToPreferredSize();
EXPECT_NE(cancel_button_width, extra_button->width());
}
TEST_F(DialogClientViewTest, ButtonPosition) {
constexpr int button_row_inset = 13;
client_view()->SetButtonRowInsets(gfx::Insets(button_row_inset));
constexpr int contents_height = 37;
constexpr int contents_width = 222;
SetSizeConstraints(gfx::Size(), gfx::Size(contents_width, contents_height),
gfx::Size(666, 666));
SetDialogButtons(ui::DIALOG_BUTTON_OK);
SizeAndLayoutWidget();
EXPECT_EQ(contents_width - button_row_inset,
client_view()->ok_button()->bounds().right());
EXPECT_EQ(contents_height + button_row_inset,
delegate()->height() + client_view()->ok_button()->y());
}
// Ensures that the focus of the button remains after a dialog update.
TEST_F(DialogClientViewTest, FocusUpdate) {
// Test with just an ok button.
widget()->Show();
SetDialogButtons(ui::DIALOG_BUTTON_OK);
EXPECT_FALSE(client_view()->ok_button()->HasFocus());
client_view()->ok_button()->RequestFocus(); // Set focus.
EXPECT_TRUE(client_view()->ok_button()->HasFocus());
delegate()->DialogModelChanged();
EXPECT_TRUE(client_view()->ok_button()->HasFocus());
}
// Ensures that the focus of the button remains after a dialog update that
// contains multiple buttons.
TEST_F(DialogClientViewTest, FocusMultipleButtons) {
// Test with ok and cancel buttons.
widget()->Show();
SetDialogButtons(ui::DIALOG_BUTTON_CANCEL | ui::DIALOG_BUTTON_OK);
EXPECT_FALSE(client_view()->ok_button()->HasFocus());
EXPECT_FALSE(client_view()->cancel_button()->HasFocus());
client_view()->cancel_button()->RequestFocus(); // Set focus.
EXPECT_FALSE(client_view()->ok_button()->HasFocus());
EXPECT_TRUE(client_view()->cancel_button()->HasFocus());
delegate()->DialogModelChanged();
EXPECT_TRUE(client_view()->cancel_button()->HasFocus());
}
// Ensures that the focus persistence works correctly when buttons are removed.
TEST_F(DialogClientViewTest, FocusChangingButtons) {
// Start with ok and cancel buttons.
widget()->Show();
SetDialogButtons(ui::DIALOG_BUTTON_CANCEL | ui::DIALOG_BUTTON_OK);
client_view()->cancel_button()->RequestFocus(); // Set focus.
FocusManager* focus_manager = delegate()->GetFocusManager();
EXPECT_EQ(client_view()->cancel_button(), focus_manager->GetFocusedView());
// Remove buttons.
SetDialogButtons(ui::DIALOG_BUTTON_NONE);
EXPECT_EQ(nullptr, focus_manager->GetFocusedView());
}
// Ensures that clicks are ignored for short time after view has been shown.
TEST_F(DialogClientViewTest, IgnorePossiblyUnintendedClicks_ClickAfterShown) {
widget()->Show();
SetDialogButtons(ui::DIALOG_BUTTON_CANCEL | ui::DIALOG_BUTTON_OK);
// Should ignore clicks right after the dialog is shown.
ui::MouseEvent mouse_event(ui::ET_MOUSE_PRESSED, gfx::PointF(), gfx::PointF(),
ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE);
test::ButtonTestApi(client_view()->ok_button()).NotifyClick(mouse_event);
test::ButtonTestApi cancel_button(client_view()->cancel_button());
cancel_button.NotifyClick(mouse_event);
EXPECT_FALSE(widget()->IsClosed());
cancel_button.NotifyClick(ui::MouseEvent(
ui::ET_MOUSE_PRESSED, gfx::PointF(), gfx::PointF(),
ui::EventTimeForNow() + base::Milliseconds(GetDoubleClickInterval()),
ui::EF_NONE, ui::EF_NONE));
EXPECT_TRUE(widget()->IsClosed());
}
// Ensures that taps are ignored for a short time after the view has been shown.
TEST_F(DialogClientViewTest, IgnorePossiblyUnintendedClicks_TapAfterShown) {
widget()->Show();
SetDialogButtons(ui::DIALOG_BUTTON_CANCEL | ui::DIALOG_BUTTON_OK);
// Should ignore taps right after the dialog is shown.
ui::GestureEvent tap_event(
0, 0, 0, ui::EventTimeForNow(),
ui::GestureEventDetails(ui::EventType::ET_GESTURE_TAP));
test::ButtonTestApi(client_view()->ok_button()).NotifyClick(tap_event);
test::ButtonTestApi cancel_button(client_view()->cancel_button());
cancel_button.NotifyClick(tap_event);
EXPECT_FALSE(widget()->IsClosed());
ui::GestureEvent tap_event2(
0, 0, 0,
ui::EventTimeForNow() + base::Milliseconds(GetDoubleClickInterval()),
ui::GestureEventDetails(ui::EventType::ET_GESTURE_TAP));
cancel_button.NotifyClick(tap_event2);
EXPECT_TRUE(widget()->IsClosed());
}
// Ensures that touch events are ignored for a short time after the view has
// been shown.
TEST_F(DialogClientViewTest, IgnorePossiblyUnintendedClicks_TouchAfterShown) {
widget()->Show();
SetDialogButtons(ui::DIALOG_BUTTON_CANCEL | ui::DIALOG_BUTTON_OK);
// Should ignore touches right after the dialog is shown.
ui::TouchEvent touch_event(ui::ET_TOUCH_PRESSED, gfx::PointF(), gfx::PointF(),
ui::EventTimeForNow(),
ui::PointerDetails(ui::EventPointerType::kTouch));
test::ButtonTestApi(client_view()->ok_button()).NotifyClick(touch_event);
test::ButtonTestApi cancel_button(client_view()->cancel_button());
cancel_button.NotifyClick(touch_event);
EXPECT_FALSE(widget()->IsClosed());
ui::TouchEvent touch_event2(
ui::ET_TOUCH_PRESSED, gfx::PointF(), gfx::PointF(),
ui::EventTimeForNow() + base::Milliseconds(GetDoubleClickInterval()),
ui::PointerDetails(ui::EventPointerType::kTouch));
cancel_button.NotifyClick(touch_event2);
EXPECT_TRUE(widget()->IsClosed());
}
// Ensures that repeated clicks with short intervals after view has been shown
// are also ignored.
TEST_F(DialogClientViewTest, IgnorePossiblyUnintendedClicks_RepeatedClicks) {
widget()->Show();
SetDialogButtons(ui::DIALOG_BUTTON_CANCEL | ui::DIALOG_BUTTON_OK);
const base::TimeTicks kNow = ui::EventTimeForNow();
const base::TimeDelta kShortClickInterval =
base::Milliseconds(GetDoubleClickInterval());
// Should ignore clicks right after the dialog is shown.
ui::MouseEvent mouse_event(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(),
kNow, ui::EF_NONE, ui::EF_NONE);
test::ButtonTestApi(client_view()->ok_button()).NotifyClick(mouse_event);
test::ButtonTestApi cancel_button(client_view()->cancel_button());
cancel_button.NotifyClick(mouse_event);
EXPECT_FALSE(widget()->IsClosed());
// Should ignore repeated clicks with short intervals, even though enough time
// has passed since the dialog was shown.
const base::TimeDelta kRepeatedClickInterval = kShortClickInterval / 2;
const size_t kNumClicks = 4;
ASSERT_TRUE(kNumClicks * kRepeatedClickInterval > kShortClickInterval);
base::TimeTicks event_time = kNow;
for (size_t i = 0; i < kNumClicks; i++) {
cancel_button.NotifyClick(ui::MouseEvent(ui::ET_MOUSE_PRESSED, gfx::Point(),
gfx::Point(), event_time,
ui::EF_NONE, ui::EF_NONE));
EXPECT_FALSE(widget()->IsClosed());
event_time += kRepeatedClickInterval;
}
// Sufficient time passed, events are now allowed.
event_time += kShortClickInterval;
cancel_button.NotifyClick(ui::MouseEvent(ui::ET_MOUSE_PRESSED, gfx::Point(),
gfx::Point(), event_time,
ui::EF_NONE, ui::EF_NONE));
EXPECT_TRUE(widget()->IsClosed());
}
TEST_F(DialogClientViewTest, ButtonLayoutWithExtra) {
// The dialog button row's layout should look like:
// | <inset> [extra] <flex-margin> [cancel] <margin> [ok] <inset> |
// Where:
// 1) The two insets are linkable
// 2) The ok & cancel buttons have their width linked
// 3) The extra button has its width linked to the other two
// 4) The margin should be invariant as the dialog changes width
// 5) The flex margin should change as the dialog changes width
//
// Note that cancel & ok may swap order depending on
// PlatformStyle::kIsOkButtonLeading; these invariants hold for either order.
SetDialogButtons(ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL);
SetDialogButtonLabel(ui::DIALOG_BUTTON_OK, u"ok");
SetDialogButtonLabel(ui::DIALOG_BUTTON_CANCEL, u"cancel");
SetExtraView(
std::make_unique<LabelButton>(Button::PressedCallback(), u"extra"));
widget()->Show();
Button* ok = GetButtonByAccessibleName(u"ok");
Button* cancel = GetButtonByAccessibleName(u"cancel");
Button* extra = GetButtonByAccessibleName(u"extra");
ASSERT_NE(ok, cancel);
ASSERT_NE(ok, extra);
ASSERT_NE(cancel, extra);
SizeAndLayoutWidget();
auto bounds_left = [](View* v) { return v->GetBoundsInScreen().x(); };
auto bounds_right = [](View* v) { return v->GetBoundsInScreen().right(); };
// (1): left inset == right inset (and they shouldn't be 0):
int left_inset = bounds_left(extra) - bounds_left(delegate());
int right_inset = bounds_right(delegate()) -
std::max(bounds_right(ok), bounds_right(cancel));
EXPECT_EQ(left_inset, right_inset);
EXPECT_GT(left_inset, 0);
// (2) & (3): All three buttons have their widths linked:
EXPECT_EQ(ok->width(), cancel->width());
EXPECT_EQ(ok->width(), extra->width());
EXPECT_GT(ok->width(), 0);
// (4): Margin between ok & cancel should be invariant as dialog width
// changes:
auto get_margin = [&]() {
return std::max(bounds_left(ok), bounds_left(cancel)) -
std::min(bounds_right(ok), bounds_right(cancel));
};
// (5): Flex margin between ok/cancel and extra should vary with dialog width
// (it should absorb 100% of the change in width)
auto get_flex_margin = [&]() {
return std::min(bounds_left(ok), bounds_left(cancel)) - bounds_right(extra);
};
int old_margin = get_margin();
int old_flex_margin = get_flex_margin();
SetSizeConstraints(gfx::Size(), gfx::Size(delegate()->width() + 100, 0),
gfx::Size());
SizeAndLayoutWidget();
EXPECT_EQ(old_margin, get_margin());
EXPECT_EQ(old_flex_margin + 100, get_flex_margin());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/window/dialog_client_view_unittest.cc | C++ | unknown | 29,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.
#include "ui/views/window/dialog_delegate.h"
#include <utility>
#include "base/debug/alias.h"
#include "base/feature_list.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "base/observer_list.h"
#include "build/build_config.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/ax_role_properties.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/gfx/color_palette.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/bubble/bubble_border.h"
#include "ui/views/bubble/bubble_frame_view.h"
#include "ui/views/buildflags.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/layout/layout_provider.h"
#include "ui/views/style/platform_style.h"
#include "ui/views/views_features.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_observer.h"
#include "ui/views/window/dialog_client_view.h"
#include "ui/views/window/dialog_observer.h"
namespace views {
// Debug information for https://crbug.com/1215247.
int g_instance_count = 0;
////////////////////////////////////////////////////////////////////////////////
// DialogDelegate::Params:
DialogDelegate::Params::Params() = default;
DialogDelegate::Params::~Params() = default;
////////////////////////////////////////////////////////////////////////////////
// DialogDelegate:
DialogDelegate::DialogDelegate() {
++g_instance_count;
WidgetDelegate::RegisterWindowWillCloseCallback(
base::BindOnce(&DialogDelegate::WindowWillClose, base::Unretained(this)));
}
// static
Widget* DialogDelegate::CreateDialogWidget(WidgetDelegate* delegate,
gfx::NativeWindow context,
gfx::NativeView parent,
gfx::AcceleratedWidget parent_widget) {
views::Widget* widget = new views::Widget;
views::Widget::InitParams params =
GetDialogWidgetInitParams(delegate, context, parent, gfx::Rect(),
parent_widget);
widget->Init(std::move(params));
return widget;
}
// static
Widget* DialogDelegate::CreateDialogWidget(
std::unique_ptr<WidgetDelegate> delegate,
gfx::NativeWindow context,
gfx::NativeView parent,
gfx::AcceleratedWidget parent_widget) {
DCHECK(delegate->owned_by_widget());
return CreateDialogWidget(delegate.release(), context, parent, parent_widget);
}
// static
bool DialogDelegate::CanSupportCustomFrame(gfx::NativeView parent,
gfx::AcceleratedWidget parent_widget) {
#if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && \
BUILDFLAG(ENABLE_DESKTOP_AURA)
// The new style doesn't support unparented dialogs on Linux desktop.
return parent != nullptr || parent_widget != gfx::kNullAcceleratedWidget;
#else
return true;
#endif
}
// static
Widget::InitParams DialogDelegate::GetDialogWidgetInitParams(
WidgetDelegate* delegate,
gfx::NativeWindow context,
gfx::NativeView parent,
const gfx::Rect& bounds,
gfx::AcceleratedWidget parent_widget) {
views::Widget::InitParams params;
params.delegate = delegate;
params.bounds = bounds;
DialogDelegate* dialog = delegate->AsDialogDelegate();
if (dialog)
dialog->params_.custom_frame &= CanSupportCustomFrame(parent, parent_widget);
if (!dialog || dialog->use_custom_frame()) {
params.opacity = Widget::InitParams::WindowOpacity::kTranslucent;
params.remove_standard_frame = true;
#if !BUILDFLAG(IS_MAC)
// Except on Mac, the bubble frame includes its own shadow; remove any
// native shadowing. On Mac, the window server provides the shadow.
params.shadow_type = views::Widget::InitParams::ShadowType::kNone;
#endif
}
params.context = context;
params.parent = parent;
params.parent_widget = parent_widget;
#if !BUILDFLAG(IS_APPLE)
// Web-modal (ui::MODAL_TYPE_CHILD) dialogs with parents are marked as child
// widgets to prevent top-level window behavior (independent movement, etc).
// On Mac, however, the parent may be a native window (not a views::Widget),
// and so the dialog must be considered top-level to gain focus and input
// method behaviors.
params.child = parent && (delegate->GetModalType() == ui::MODAL_TYPE_CHILD);
#endif
return params;
}
int DialogDelegate::GetDefaultDialogButton() const {
if (GetParams().default_button.has_value())
return *GetParams().default_button;
if (GetDialogButtons() & ui::DIALOG_BUTTON_OK)
return ui::DIALOG_BUTTON_OK;
if (GetDialogButtons() & ui::DIALOG_BUTTON_CANCEL)
return ui::DIALOG_BUTTON_CANCEL;
return ui::DIALOG_BUTTON_NONE;
}
std::u16string DialogDelegate::GetDialogButtonLabel(
ui::DialogButton button) const {
if (!GetParams().button_labels[button].empty())
return GetParams().button_labels[button];
if (button == ui::DIALOG_BUTTON_OK)
return l10n_util::GetStringUTF16(IDS_APP_OK);
CHECK_EQ(button, ui::DIALOG_BUTTON_CANCEL);
return GetDialogButtons() & ui::DIALOG_BUTTON_OK
? l10n_util::GetStringUTF16(IDS_APP_CANCEL)
: l10n_util::GetStringUTF16(IDS_APP_CLOSE);
}
bool DialogDelegate::IsDialogButtonEnabled(ui::DialogButton button) const {
return params_.enabled_buttons & button;
}
bool DialogDelegate::Cancel() {
DCHECK(!already_started_close_);
if (cancel_callback_)
RunCloseCallback(std::move(cancel_callback_));
return true;
}
bool DialogDelegate::Accept() {
DCHECK(!already_started_close_);
if (accept_callback_)
RunCloseCallback(std::move(accept_callback_));
return true;
}
void DialogDelegate::RunCloseCallback(base::OnceClosure callback) {
DCHECK(!already_started_close_);
already_started_close_ = true;
std::move(callback).Run();
}
View* DialogDelegate::GetInitiallyFocusedView() {
if (WidgetDelegate::HasConfiguredInitiallyFocusedView())
return WidgetDelegate::GetInitiallyFocusedView();
// Focus the default button if any.
const DialogClientView* dcv = GetDialogClientView();
if (!dcv)
return nullptr;
int default_button = GetDefaultDialogButton();
if (default_button == ui::DIALOG_BUTTON_NONE)
return nullptr;
// The default button should be a button we have.
CHECK(default_button & GetDialogButtons());
if (default_button & ui::DIALOG_BUTTON_OK)
return dcv->ok_button();
if (default_button & ui::DIALOG_BUTTON_CANCEL)
return dcv->cancel_button();
return nullptr;
}
DialogDelegate* DialogDelegate::AsDialogDelegate() {
return this;
}
ClientView* DialogDelegate::CreateClientView(Widget* widget) {
return new DialogClientView(widget, TransferOwnershipOfContentsView());
}
std::unique_ptr<NonClientFrameView> DialogDelegate::CreateNonClientFrameView(
Widget* widget) {
return use_custom_frame() ? CreateDialogFrameView(widget)
: WidgetDelegate::CreateNonClientFrameView(widget);
}
void DialogDelegate::WindowWillClose() {
if (already_started_close_)
return;
bool new_callback_present =
close_callback_ || cancel_callback_ || accept_callback_;
if (close_callback_)
RunCloseCallback(std::move(close_callback_));
if (new_callback_present)
return;
// This is set here instead of before the invocations of Accept()/Cancel() so
// that those methods can DCHECK that !already_started_close_. Otherwise,
// client code could (eg) call Accept() from inside the cancel callback, which
// could lead to multiple callbacks being delivered from this class.
already_started_close_ = true;
}
bool DialogDelegate::EscShouldCancelDialog() const {
// Use cancel as the Esc action if there's no defined "close" action. If the
// delegate has either specified a closing action or a close-x they can expect
// it to be called on Esc.
return !close_callback_ && !ShouldShowCloseButton();
}
// static
std::unique_ptr<NonClientFrameView> DialogDelegate::CreateDialogFrameView(
Widget* widget) {
LayoutProvider* provider = LayoutProvider::Get();
auto frame = std::make_unique<BubbleFrameView>(
provider->GetInsetsMetric(INSETS_DIALOG_TITLE), gfx::Insets());
const BubbleBorder::Shadow kShadow = BubbleBorder::DIALOG_SHADOW;
std::unique_ptr<BubbleBorder> border =
std::make_unique<BubbleBorder>(BubbleBorder::FLOAT, kShadow);
DialogDelegate* delegate = widget->widget_delegate()->AsDialogDelegate();
if (delegate) {
if (delegate->GetParams().round_corners)
border->SetCornerRadius(delegate->GetCornerRadius());
frame->SetFootnoteView(delegate->DisownFootnoteView());
}
frame->SetBubbleBorder(std::move(border));
return frame;
}
const DialogClientView* DialogDelegate::GetDialogClientView() const {
if (!GetWidget())
return nullptr;
const views::View* client_view = GetWidget()->client_view();
return client_view->GetClassName() == DialogClientView::kViewClassName
? static_cast<const DialogClientView*>(client_view)
: nullptr;
}
DialogClientView* DialogDelegate::GetDialogClientView() {
return const_cast<DialogClientView*>(
const_cast<const DialogDelegate*>(this)->GetDialogClientView());
}
BubbleFrameView* DialogDelegate::GetBubbleFrameView() const {
if (!use_custom_frame())
return nullptr;
const NonClientView* view =
GetWidget() ? GetWidget()->non_client_view() : nullptr;
return view ? static_cast<BubbleFrameView*>(view->frame_view()) : nullptr;
}
views::LabelButton* DialogDelegate::GetOkButton() const {
DCHECK(GetWidget()) << "Don't call this before OnWidgetInitialized";
auto* client = GetDialogClientView();
return client ? client->ok_button() : nullptr;
}
views::LabelButton* DialogDelegate::GetCancelButton() const {
DCHECK(GetWidget()) << "Don't call this before OnWidgetInitialized";
auto* client = GetDialogClientView();
return client ? client->cancel_button() : nullptr;
}
views::View* DialogDelegate::GetExtraView() const {
DCHECK(GetWidget()) << "Don't call this before OnWidgetInitialized";
auto* client = GetDialogClientView();
return client ? client->extra_view() : nullptr;
}
views::View* DialogDelegate::GetFootnoteViewForTesting() const {
if (!GetWidget())
return footnote_view_.get();
NonClientFrameView* frame = GetWidget()->non_client_view()->frame_view();
// CreateDialogFrameView above always uses BubbleFrameView. There are
// subclasses that override CreateDialogFrameView, but none of them override
// it to create anything other than a BubbleFrameView.
// TODO(https://crbug.com/1011446): Make CreateDialogFrameView final, then
// remove this DCHECK.
DCHECK_EQ(frame->GetClassName(), BubbleFrameView::kViewClassName);
return static_cast<BubbleFrameView*>(frame)->GetFootnoteView();
}
void DialogDelegate::AddObserver(DialogObserver* observer) {
observer_list_.AddObserver(observer);
}
void DialogDelegate::RemoveObserver(DialogObserver* observer) {
observer_list_.RemoveObserver(observer);
}
void DialogDelegate::DialogModelChanged() {
for (DialogObserver& observer : observer_list_)
observer.OnDialogChanged();
}
void DialogDelegate::TriggerInputProtection() {
GetDialogClientView()->TriggerInputProtection();
}
void DialogDelegate::SetDefaultButton(int button) {
if (params_.default_button == button)
return;
params_.default_button = button;
DialogModelChanged();
}
void DialogDelegate::SetButtons(int buttons) {
if (params_.buttons == buttons)
return;
params_.buttons = buttons;
DialogModelChanged();
}
void DialogDelegate::SetButtonEnabled(ui::DialogButton button, bool enabled) {
if (!!(params_.enabled_buttons & button) == enabled)
return;
if (enabled)
params_.enabled_buttons |= button;
else
params_.enabled_buttons &= ~button;
DialogModelChanged();
}
void DialogDelegate::SetButtonLabel(ui::DialogButton button,
std::u16string label) {
if (params_.button_labels[button] == label)
return;
params_.button_labels[button] = label;
DialogModelChanged();
}
void DialogDelegate::SetAcceptCallback(base::OnceClosure callback) {
accept_callback_ = std::move(callback);
}
void DialogDelegate::SetCancelCallback(base::OnceClosure callback) {
cancel_callback_ = std::move(callback);
}
void DialogDelegate::SetCloseCallback(base::OnceClosure callback) {
close_callback_ = std::move(callback);
}
std::unique_ptr<View> DialogDelegate::DisownExtraView() {
return std::move(extra_view_);
}
bool DialogDelegate::Close() {
WindowWillClose();
return true;
}
void DialogDelegate::ResetViewShownTimeStampForTesting() {
GetDialogClientView()->ResetViewShownTimeStampForTesting();
}
void DialogDelegate::SetButtonRowInsets(const gfx::Insets& insets) {
GetDialogClientView()->SetButtonRowInsets(insets);
}
void DialogDelegate::AcceptDialog() {
// Copy the dialog widget name onto the stack so it appears in crash dumps.
DEBUG_ALIAS_FOR_CSTR(last_widget_name, GetWidget()->GetName().c_str(), 64);
DCHECK(IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
if (already_started_close_ || !Accept())
return;
// Check for Accept() deleting `this` but returning false. Empirically the
// steady state instance count with no dialogs open is zero, so if it's back
// to zero `this` is deleted https://crbug.com/1215247
if (g_instance_count <= 0) {
// LOG(FATAL) instead of CHECK() to put the widget name into a crash key.
// See "Product Data" in the crash tool if a crash report shows this line.
LOG(FATAL) << last_widget_name;
}
already_started_close_ = true;
GetWidget()->CloseWithReason(
views::Widget::ClosedReason::kAcceptButtonClicked);
}
void DialogDelegate::CancelDialog() {
// If there's a close button available, this callback should only be reachable
// if the cancel button is available. Otherwise this can be reached through
// closing the dialog via Esc.
if (ShouldShowCloseButton())
DCHECK(IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
if (already_started_close_ || !Cancel())
return;
already_started_close_ = true;
GetWidget()->CloseWithReason(
views::Widget::ClosedReason::kCancelButtonClicked);
}
DialogDelegate::~DialogDelegate() {
--g_instance_count;
}
ax::mojom::Role DialogDelegate::GetAccessibleWindowRole() {
return ax::mojom::Role::kDialog;
}
int DialogDelegate::GetCornerRadius() const {
#if BUILDFLAG(IS_MAC)
// TODO(crbug.com/1116680): On Mac MODAL_TYPE_WINDOW is implemented using
// sheets which causes visual artifacts when corner radius is increased for
// modal types. Remove this after this issue has been addressed.
if (GetModalType() == ui::MODAL_TYPE_WINDOW)
return 2;
#endif
if (params_.corner_radius)
return *params_.corner_radius;
return LayoutProvider::Get()->GetCornerRadiusMetric(
views::ShapeContextTokens::kDialogRadius);
}
std::unique_ptr<View> DialogDelegate::DisownFootnoteView() {
return std::move(footnote_view_);
}
////////////////////////////////////////////////////////////////////////////////
// DialogDelegateView:
DialogDelegateView::DialogDelegateView() {
SetOwnedByWidget(true);
}
DialogDelegateView::~DialogDelegateView() = default;
Widget* DialogDelegateView::GetWidget() {
return View::GetWidget();
}
const Widget* DialogDelegateView::GetWidget() const {
return View::GetWidget();
}
View* DialogDelegateView::GetContentsView() {
return this;
}
BEGIN_METADATA(DialogDelegateView, View)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/window/dialog_delegate.cc | C++ | unknown | 15,667 |
// 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_WINDOW_DIALOG_DELEGATE_H_
#define UI_VIEWS_WINDOW_DIALOG_DELEGATE_H_
#include <memory>
#include <string>
#include <utility>
#include "base/compiler_specific.h"
#include "base/observer_list.h"
#include "base/time/time.h"
#include "ui/accessibility/ax_enums.mojom-forward.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/ui_base_types.h"
#include "ui/views/metadata/view_factory.h"
#include "ui/views/view.h"
#include "ui/views/views_export.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
namespace views {
class BubbleFrameView;
class DialogClientView;
class DialogObserver;
class LabelButton;
///////////////////////////////////////////////////////////////////////////////
//
// DialogDelegate
//
// DialogDelegate is an interface implemented by objects that wish to show a
// dialog box Window. The window that is displayed uses this interface to
// determine how it should be displayed and notify the delegate object of
// certain events.
//
// If possible, it is better to compose DialogDelegate rather than subclassing
// it; it has many setters, including some inherited from WidgetDelegate, that
// let you set properties on it without overriding virtuals. Doing this also
// means you do not need to deal with implementing ::DeleteDelegate().
//
///////////////////////////////////////////////////////////////////////////////
class VIEWS_EXPORT DialogDelegate : public WidgetDelegate {
public:
struct Params {
Params();
~Params();
absl::optional<int> default_button = absl::nullopt;
bool round_corners = true;
absl::optional<int> corner_radius = absl::nullopt;
bool draggable = false;
// Whether to use the Views-styled frame (if true) or a platform-native
// frame if false. In general, dialogs that look like fully separate windows
// should use the platform-native frame, and all other dialogs should use
// the Views-styled one.
bool custom_frame = true;
// A bitmask of buttons (from ui::DialogButton) that are present in this
// dialog.
int buttons = ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL;
// Text labels for the buttons on this dialog. Any button without a label
// here will get the default text for its type from GetDialogButtonLabel.
// Prefer to use this field (via SetButtonLabel) rather than override
// GetDialogButtonLabel - see https://crbug.com/1011446
std::u16string button_labels[ui::DIALOG_BUTTON_LAST + 1];
// A bitmask of buttons (from ui::DialogButton) that are enabled in this
// dialog. It's legal for a button to be marked enabled that isn't present
// in |buttons| (see above).
int enabled_buttons = ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL;
};
DialogDelegate();
DialogDelegate(const DialogDelegate&) = delete;
DialogDelegate& operator=(const DialogDelegate&) = delete;
~DialogDelegate() override;
// Creates a widget at a default location.
// There are two variant of this method. The newer one is the unique_ptr
// method, which simply takes ownership of the WidgetDelegate and passes it to
// the created Widget. When using the unique_ptr version, it is required that
// delegate->owned_by_widget(). Unless you have a good reason, you should use
// this variant.
//
// If !delegate->owned_by_widget() *or* if your WidgetDelegate subclass has a
// custom override of WidgetDelegate::DeleteDelegate, use the raw pointer
// variant instead, and please talk to one of the //ui/views owners about
// your use case.
static Widget* CreateDialogWidget(std::unique_ptr<WidgetDelegate> delegate,
gfx::NativeWindow context,
gfx::NativeView parent,
gfx::AcceleratedWidget parent_widget =
gfx::kNullAcceleratedWidget);
static Widget* CreateDialogWidget(WidgetDelegate* delegate,
gfx::NativeWindow context,
gfx::NativeView parent,
gfx::AcceleratedWidget parent_widget =
gfx::kNullAcceleratedWidget);
// Whether using custom dialog frame is supported for this dialog.
static bool CanSupportCustomFrame(gfx::NativeView parent,
gfx::AcceleratedWidget parent_widget);
// Returns the dialog widget InitParams for a given |context| or |parent|.
// If |bounds| is not empty, used to initially place the dialog, otherwise
// a default location is used.
static Widget::InitParams GetDialogWidgetInitParams(WidgetDelegate* delegate,
gfx::NativeWindow context,
gfx::NativeView parent,
const gfx::Rect& bounds,
gfx::AcceleratedWidget parent_widget =
gfx::kNullAcceleratedWidget);
// Returns a mask specifying which of the available DialogButtons are visible
// for the dialog.
// TODO(https://crbug.com/1011446): Rename this to buttons().
int GetDialogButtons() const { return params_.buttons; }
// Returns the default dialog button. This should not be a mask as only
// one button should ever be the default button. Return
// ui::DIALOG_BUTTON_NONE if there is no default. Default
// behavior is to return ui::DIALOG_BUTTON_OK or
// ui::DIALOG_BUTTON_CANCEL (in that order) if they are
// present, ui::DIALOG_BUTTON_NONE otherwise.
int GetDefaultDialogButton() const;
// Returns the label of the specified dialog button.
std::u16string GetDialogButtonLabel(ui::DialogButton button) const;
// Returns whether the specified dialog button is enabled.
virtual bool IsDialogButtonEnabled(ui::DialogButton button) const;
// For Dialog boxes, if there is a "Cancel" button or no dialog button at all,
// this is called when the user presses the "Cancel" button. This function
// should return true if the window can be closed after it returns, or false
// if it must remain open. By default, return true without doing anything.
// DEPRECATED: use |SetCancelCallback| instead.
virtual bool Cancel();
// For Dialog boxes, this is called when the user presses the "OK" button, or
// the Enter key. This function should return true if the window can be closed
// after it returns, or false if it must remain open. By default, return true
// without doing anything.
// DEPRECATED: use |SetAcceptCallback| instead.
virtual bool Accept();
// Overridden from WidgetDelegate:
View* GetInitiallyFocusedView() override;
DialogDelegate* AsDialogDelegate() override;
ClientView* CreateClientView(Widget* widget) override;
std::unique_ptr<NonClientFrameView> CreateNonClientFrameView(
Widget* widget) override;
static std::unique_ptr<NonClientFrameView> CreateDialogFrameView(
Widget* widget);
const gfx::Insets& margins() const { return margins_; }
void set_margins(const gfx::Insets& margins) { margins_ = margins; }
// Set a fixed width for the dialog. Used by DialogClientView.
void set_fixed_width(int fixed_width) { fixed_width_ = fixed_width; }
int fixed_width() const { return fixed_width_; }
template <typename T>
T* SetExtraView(std::unique_ptr<T> extra_view) {
T* view = extra_view.get();
extra_view_ = std::move(extra_view);
return view;
}
template <typename T>
T* SetFootnoteView(std::unique_ptr<T> footnote_view) {
T* view = footnote_view.get();
footnote_view_ = std::move(footnote_view);
return view;
}
// Returns the BubbleFrameView of this dialog delegate. A bubble frame view
// will only be created when use_custom_frame() is true.
BubbleFrameView* GetBubbleFrameView() const;
// A helper for accessing the DialogClientView object contained by this
// delegate's Window. This function can return nullptr if the |client_view| is
// a DialogClientView subclass which also has metadata or overrides
// GetClassName().
const DialogClientView* GetDialogClientView() const;
DialogClientView* GetDialogClientView();
// Helpers for accessing parts of the DialogClientView without needing to know
// about DialogClientView. Do not call these before OnWidgetInitialized().
views::LabelButton* GetOkButton() const;
views::LabelButton* GetCancelButton() const;
views::View* GetExtraView() const;
// Helper for accessing the footnote view. Unlike the three methods just
// above, this *is* safe to call before OnWidgetInitialized().
views::View* GetFootnoteViewForTesting() const;
// Add or remove an observer notified by calls to DialogModelChanged().
void AddObserver(DialogObserver* observer);
void RemoveObserver(DialogObserver* observer);
// Notifies DialogDelegate that the result of one of the virtual getter
// functions above has changed, which causes it to rebuild its layout. It is
// not necessary to call this unless you are overriding
// IsDialogButtonEnabled() or manually manipulating the dialog buttons.
// TODO(https://crbug.com/1011446): Make this private.
void DialogModelChanged();
// Input protection is triggered upon prompt creation and updated on
// visibility changes. Other situations such as top window changes in certain
// situations should trigger the input protection manually by calling this
// method. Input protection protects against certain kinds of clickjacking.
// Essentially it prevents clicks that happen within a user's double click
// interval from when the protection is started as well as any following
// clicks that happen in shorter succession than the user's double click
// interval. Refer to InputEventActivationProtector for more information.
void TriggerInputProtection();
void set_use_round_corners(bool round) { params_.round_corners = round; }
void set_corner_radius(int corner_radius) {
params_.corner_radius = corner_radius;
}
const absl::optional<int> corner_radius() const {
return params_.corner_radius;
}
void set_draggable(bool draggable) { params_.draggable = draggable; }
bool draggable() const { return params_.draggable; }
void set_use_custom_frame(bool use) { params_.custom_frame = use; }
bool use_custom_frame() const { return params_.custom_frame; }
// These methods internally call DialogModelChanged() if needed, so it is not
// necessary to call DialogModelChanged() yourself after calling them.
void SetDefaultButton(int button);
void SetButtons(int buttons);
void SetButtonLabel(ui::DialogButton button, std::u16string label);
void SetButtonEnabled(ui::DialogButton button, bool enabled);
// Called when the user presses the dialog's "OK" button or presses the dialog
// accept accelerator, if there is one.
void SetAcceptCallback(base::OnceClosure callback);
// Called when the user presses the dialog's "Cancel" button or presses the
// dialog close accelerator (which is always VKEY_ESCAPE).
void SetCancelCallback(base::OnceClosure callback);
// Called when:
// * The user presses the dialog's close button, if it has one
// * The dialog's widget is closed via Widget::Close()
// NOT called when the dialog's widget is closed via Widget::CloseNow() - in
// that case, the normal widget close path is skipped, so no orderly teardown
// of the dialog's widget happens. The main way that can happen in production
// use is if the dialog's parent widget is closed.
void SetCloseCallback(base::OnceClosure callback);
// Returns ownership of the extra view for this dialog, if one was provided
// via SetExtraView(). This is only for use by DialogClientView; don't call
// it.
// It would be good to instead have a DialogClientView::SetExtraView method
// that passes ownership into DialogClientView once. Unfortunately doing this
// broke a bunch of tests in a subtle way: the obvious place to call
// DCV::SetExtraView was from DD::OnWidgetInitialized. DCV::SetExtraView
// would then add the new view to DCV, which would invalidate its layout.
// However, many tests were doing essentially this:
//
// TestDialogDelegate delegate;
// ShowBubble(&delegate);
// TryToUseExtraView();
//
// and then trying to use the extra view's bounds, most commonly by
// synthesizing mouse clicks on it. At this point the extra view's layout is
// invalid *but* it has not yet been laid out, because View::InvalidateLayout
// schedules a deferred re-layout later. The design where DCV pulls the extra
// view from DD doesn't have this issue: during the initial construction of
// DCV, DCV fetches the extra view and slots it into its layout, and then the
// initial layout pass in Widget::Init causes the extra view to get laid out.
// Deferring inserting the extra view until after Widget::Init has finished is
// what causes the extra view to not be laid out (and hence the tests to
// fail).
//
// Potential future fixes:
// 1) The tests could manually force a re-layout here, or
// 2) The tests could be rewritten to not depend on the extra view's
// bounds, by not trying to deliver mouse events to it somehow, or
// 3) DCV::SetupLayout could always force an explicit Layout, ignoring the
// lazy layout system in View::InvalidateLayout
std::unique_ptr<View> DisownExtraView();
// Accept or cancel the dialog, as though the user had pressed the
// Accept/Cancel buttons. These methods:
// 1) Invoke the DialogDelegate's Cancel or Accept methods
// 2) Depending on their return value, close the dialog's widget.
// Neither of these methods can be called before the dialog has been
// initialized.
// NOT_TAIL_CALLED forces the calling function to appear on the stack in
// crash dumps. https://crbug.com/1215247
NOT_TAIL_CALLED void AcceptDialog();
void CancelDialog();
// This method invokes the behavior that *would* happen if this dialog's
// containing widget were closed. It is present only as a compatibility shim
// for unit tests; do not add new calls to it.
// TODO(https://crbug.com/1011446): Delete this.
bool Close();
// Reset the dialog's shown timestamp, for tests that are subject to the
// "unintended interaction" detection mechanism.
void ResetViewShownTimeStampForTesting();
// Set the insets used for the dialog's button row. This should be used only
// rarely.
// TODO(ellyjones): Investigate getting rid of this entirely and having all
// dialogs use the same button row insets.
void SetButtonRowInsets(const gfx::Insets& insets);
// Callback for WidgetDelegate when the window this dialog is hosted in is
// closing. Don't call this yourself.
void WindowWillClose();
// Returns whether the delegate's CancelDialog() should be called instead of
// closing the Widget when Esc is pressed. Called by DialogClientView.
bool EscShouldCancelDialog() const;
protected:
// Overridden from WidgetDelegate:
ax::mojom::Role GetAccessibleWindowRole() override;
const Params& GetParams() const { return params_; }
int GetCornerRadius() const;
// Return ownership of the footnote view for this dialog. Only use this in
// subclass overrides of CreateNonClientFrameView.
std::unique_ptr<View> DisownFootnoteView();
private:
// Runs a close callback, ensuring that at most one close callback is ever
// run.
void RunCloseCallback(base::OnceClosure callback);
// The margins between the content and the inside of the border.
// TODO(crbug.com/733040): Most subclasses assume they must set their own
// margins explicitly, so we set them to 0 here for now to avoid doubled
// margins.
gfx::Insets margins_{0};
// Use a fixed dialog width for dialog. Used by DialogClientView.
int fixed_width_ = 0;
// Dialog parameters for this dialog.
Params params_;
// The extra view for this dialog, if there is one.
std::unique_ptr<View> extra_view_;
// The footnote view for this dialog, if there is one.
std::unique_ptr<View> footnote_view_;
// Observers for DialogModel changes.
base::ObserverList<DialogObserver>::Unchecked observer_list_;
// Callbacks for the dialog's actions:
base::OnceClosure accept_callback_;
base::OnceClosure cancel_callback_;
base::OnceClosure close_callback_;
// Whether any of the three callbacks just above has been delivered yet, *or*
// one of the Accept/Cancel methods have been called and returned true.
bool already_started_close_ = false;
};
// A DialogDelegate implementation that is-a View. Used to override GetWidget()
// to call View's GetWidget() for the common case where a DialogDelegate
// implementation is-a View. Note that DialogDelegateView is not owned by
// view's hierarchy and is expected to be deleted on DeleteDelegate call.
//
// It is best not to add new uses of this class, and instead to subclass View
// directly and have a DialogDelegate member that you configure - essentially,
// to compose with DialogDelegate rather than inheriting from it.
// DialogDelegateView has unusual lifetime semantics that you can avoid dealing
// with, and your class will be smaller.
class VIEWS_EXPORT DialogDelegateView : public DialogDelegate, public View {
public:
METADATA_HEADER(DialogDelegateView);
DialogDelegateView();
DialogDelegateView(const DialogDelegateView&) = delete;
DialogDelegateView& operator=(const DialogDelegateView&) = delete;
~DialogDelegateView() override;
// DialogDelegate:
Widget* GetWidget() override;
const Widget* GetWidget() const override;
View* GetContentsView() override;
};
// Explicitly instantiate the following templates to ensure proper linking,
// especially when using GCC.
template View* DialogDelegate::SetExtraView<View>(std::unique_ptr<View>);
template View* DialogDelegate::SetFootnoteView<View>(std::unique_ptr<View>);
BEGIN_VIEW_BUILDER(VIEWS_EXPORT, DialogDelegateView, View)
VIEW_BUILDER_PROPERTY(ax::mojom::Role, AccessibleWindowRole)
VIEW_BUILDER_PROPERTY(std::u16string, AccessibleTitle)
VIEW_BUILDER_PROPERTY(bool, CanMaximize)
VIEW_BUILDER_PROPERTY(bool, CanMinimize)
VIEW_BUILDER_PROPERTY(bool, CanResize)
VIEW_BUILDER_VIEW_TYPE_PROPERTY(views::View, ExtraView)
VIEW_BUILDER_VIEW_TYPE_PROPERTY(views::View, FootnoteView)
VIEW_BUILDER_PROPERTY(bool, FocusTraversesOut)
VIEW_BUILDER_PROPERTY(bool, EnableArrowKeyTraversal)
VIEW_BUILDER_PROPERTY(ui::ImageModel, Icon)
VIEW_BUILDER_PROPERTY(ui::ImageModel, AppIcon)
VIEW_BUILDER_PROPERTY(ui::ModalType, ModalType)
VIEW_BUILDER_PROPERTY(bool, OwnedByWidget)
VIEW_BUILDER_PROPERTY(bool, ShowCloseButton)
VIEW_BUILDER_PROPERTY(bool, ShowIcon)
VIEW_BUILDER_PROPERTY(bool, ShowTitle)
VIEW_BUILDER_OVERLOAD_METHOD_CLASS(WidgetDelegate,
SetTitle,
const std::u16string&)
VIEW_BUILDER_OVERLOAD_METHOD_CLASS(WidgetDelegate, SetTitle, int)
#if defined(USE_AURA)
VIEW_BUILDER_PROPERTY(bool, CenterTitle)
#endif
VIEW_BUILDER_PROPERTY(int, Buttons)
VIEW_BUILDER_PROPERTY(int, DefaultButton)
VIEW_BUILDER_METHOD(SetButtonLabel, ui::DialogButton, std::u16string)
VIEW_BUILDER_METHOD(SetButtonEnabled, ui::DialogButton, bool)
VIEW_BUILDER_METHOD(set_margins, gfx::Insets)
VIEW_BUILDER_METHOD(set_use_round_corners, bool)
VIEW_BUILDER_METHOD(set_corner_radius, int)
VIEW_BUILDER_METHOD(set_draggable, bool)
VIEW_BUILDER_METHOD(set_use_custom_frame, bool)
VIEW_BUILDER_METHOD(set_fixed_width, int)
VIEW_BUILDER_PROPERTY(base::OnceClosure, AcceptCallback)
VIEW_BUILDER_PROPERTY(base::OnceClosure, CancelCallback)
VIEW_BUILDER_PROPERTY(base::OnceClosure, CloseCallback)
VIEW_BUILDER_PROPERTY(const gfx::Insets&, ButtonRowInsets)
END_VIEW_BUILDER
} // namespace views
DEFINE_VIEW_BUILDER(VIEWS_EXPORT, DialogDelegateView)
#endif // UI_VIEWS_WINDOW_DIALOG_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/window/dialog_delegate.h | C++ | unknown | 20,165 |
// 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 "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind.h"
#include "build/build_config.h"
#include "ui/base/hit_test.h"
#include "ui/events/event_processor.h"
#include "ui/views/bubble/bubble_border.h"
#include "ui/views/bubble/bubble_frame_view.h"
#include "ui/views/controls/button/checkbox.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/style/platform_style.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/test/views_test_utils.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_delegate.h"
#if BUILDFLAG(IS_MAC)
#include "ui/base/test/scoped_fake_full_keyboard_access.h"
#endif
namespace views {
namespace {
class TestDialog : public DialogDelegateView {
public:
TestDialog() : input_(new views::Textfield()) {
DialogDelegate::set_draggable(true);
AddChildView(input_.get());
}
TestDialog(const TestDialog&) = delete;
TestDialog& operator=(const TestDialog&) = delete;
~TestDialog() override = default;
void Init() {
// Add the accelerator before being added to the widget hierarchy (before
// DCV has registered its accelerator) to make sure accelerator handling is
// not dependent on the order of AddAccelerator calls.
EXPECT_FALSE(GetWidget());
AddAccelerator(ui::Accelerator(ui::VKEY_ESCAPE, ui::EF_NONE));
}
// WidgetDelegate overrides:
bool ShouldShowWindowTitle() const override { return !title_.empty(); }
bool ShouldShowCloseButton() const override { return show_close_button_; }
// DialogDelegateView overrides:
gfx::Size CalculatePreferredSize() const override {
return gfx::Size(200, 200);
}
bool AcceleratorPressed(const ui::Accelerator& accelerator) override {
return should_handle_escape_;
}
std::u16string GetWindowTitle() const override { return title_; }
View* GetInitiallyFocusedView() override { return input_; }
void TearDown() {
GetWidget()->Close();
}
void set_title(const std::u16string& title) { title_ = title; }
void set_show_close_button(bool show_close) {
show_close_button_ = show_close;
}
void set_should_handle_escape(bool should_handle_escape) {
should_handle_escape_ = should_handle_escape;
}
views::Textfield* input() { return input_; }
private:
raw_ptr<views::Textfield> input_;
std::u16string title_;
bool show_close_button_ = true;
bool should_handle_escape_ = false;
};
class DialogTest : public ViewsTestBase {
public:
DialogTest() = default;
DialogTest(const DialogTest&) = delete;
DialogTest& operator=(const DialogTest&) = delete;
~DialogTest() override = default;
void SetUp() override {
ViewsTestBase::SetUp();
// These tests all expect to use a custom frame on the dialog so they can
// control hit-testing and other behavior. Custom frames are only supported
// with a parent widget, so create the parent widget here.
parent_widget_ = CreateTestWidget();
parent_widget_->Show();
InitializeDialog();
ShowDialog();
}
void TearDown() override {
dialog_->TearDown();
parent_widget_.reset();
ViewsTestBase::TearDown();
}
void InitializeDialog() {
if (dialog_)
dialog_->TearDown();
dialog_ = new TestDialog();
dialog_->Init();
dialog_->SetAcceptCallback(
base::BindLambdaForTesting([&]() { accepted_ = true; }));
dialog_->SetCancelCallback(
base::BindLambdaForTesting([&]() { cancelled_ = true; }));
dialog_->SetCloseCallback(
base::BindLambdaForTesting([&]() { closed_ = true; }));
}
views::Widget* CreateDialogWidget(DialogDelegate* dialog) {
views::Widget* widget = DialogDelegate::CreateDialogWidget(
dialog, GetContext(), parent_widget_->GetNativeView());
return widget;
}
void ShowDialog() { CreateDialogWidget(dialog_)->Show(); }
void SimulateKeyPress(ui::KeyboardCode key) {
ui::KeyEvent event(ui::ET_KEY_PRESSED, key, ui::EF_NONE);
if (dialog()->GetFocusManager()->OnKeyEvent(event))
dialog()->GetWidget()->OnKeyEvent(&event);
}
TestDialog* dialog() const { return dialog_; }
views::Widget* parent_widget() { return parent_widget_.get(); }
protected:
bool accepted_ = false;
bool cancelled_ = false;
bool closed_ = false;
private:
std::unique_ptr<views::Widget> parent_widget_;
raw_ptr<TestDialog> dialog_ = nullptr;
};
} // namespace
TEST_F(DialogTest, InputIsInitiallyFocused) {
EXPECT_EQ(dialog()->input(), dialog()->GetFocusManager()->GetFocusedView());
}
TEST_F(DialogTest, OkButtonAccepts) {
EXPECT_FALSE(accepted_);
SimulateKeyPress(ui::VKEY_RETURN);
EXPECT_TRUE(accepted_);
}
TEST_F(DialogTest, EscButtonClosesDialogWithCloseButtonWithoutCallingCancel) {
// Showing the close button should be sufficient to call close on Esc (even if
// there's no close callback), we verify this by making sure that Cancel
// doesn't get called as best-effort verification.
dialog()->set_show_close_button(true);
dialog()->SetCloseCallback(base::OnceClosure());
EXPECT_FALSE(cancelled_);
SimulateKeyPress(ui::VKEY_ESCAPE);
EXPECT_FALSE(cancelled_);
}
TEST_F(DialogTest, EscButtonClosesWithCloseCallback) {
// The dialog's close callback should be called even if there's no close-x.
// See crbug.com/1245127.
dialog()->set_show_close_button(false);
EXPECT_FALSE(closed_);
SimulateKeyPress(ui::VKEY_ESCAPE);
EXPECT_TRUE(closed_);
}
TEST_F(DialogTest, EscButtonCancelsWithoutCloseAction) {
// If there's no close-x or close callback then the cancelled action should be
// called.
dialog()->SetCloseCallback(base::OnceClosure());
dialog()->set_show_close_button(false);
EXPECT_FALSE(cancelled_);
SimulateKeyPress(ui::VKEY_ESCAPE);
EXPECT_TRUE(cancelled_);
}
TEST_F(DialogTest, ReturnDirectedToOkButtonPlatformStyle) {
const ui::KeyEvent return_event(ui::ET_KEY_PRESSED, ui::VKEY_RETURN,
ui::EF_NONE);
if (PlatformStyle::kReturnClicksFocusedControl) {
EXPECT_TRUE(dialog()->GetOkButton()->OnKeyPressed(return_event));
EXPECT_TRUE(accepted_);
} else {
EXPECT_FALSE(dialog()->GetOkButton()->OnKeyPressed(return_event));
EXPECT_FALSE(accepted_);
// If the return key press was not directed *specifically* to the Ok button,
// it would bubble upwards here, reach the dialog, and accept it. The
// OkButtonAccepts test above covers that behavior.
}
}
TEST_F(DialogTest, ReturnDirectedToCancelButtonPlatformBehavior) {
const ui::KeyEvent return_event(ui::ET_KEY_PRESSED, ui::VKEY_RETURN,
ui::EF_NONE);
if (PlatformStyle::kReturnClicksFocusedControl) {
EXPECT_TRUE(dialog()->GetCancelButton()->OnKeyPressed(return_event));
EXPECT_TRUE(cancelled_);
} else {
EXPECT_FALSE(dialog()->GetCancelButton()->OnKeyPressed(return_event));
EXPECT_FALSE(cancelled_);
// If the return key press was not directed *specifically* to the Ok button,
// it would bubble upwards here, reach the dialog, and accept it. The
// OkButtonAccepts test above covers that behavior.
}
}
// Unlike the previous two tests, this test simulates a key press at the level
// of the dialog's Widget, so the return-to-close-dialog behavior does happen.
TEST_F(DialogTest, ReturnOnCancelButtonPlatformBehavior) {
dialog()->GetCancelButton()->RequestFocus();
SimulateKeyPress(ui::VKEY_RETURN);
if (PlatformStyle::kReturnClicksFocusedControl) {
EXPECT_TRUE(cancelled_);
} else {
EXPECT_TRUE(accepted_);
}
}
TEST_F(DialogTest, CanOverrideEsc) {
dialog()->set_should_handle_escape(true);
SimulateKeyPress(ui::VKEY_ESCAPE);
EXPECT_FALSE(cancelled_);
EXPECT_FALSE(closed_);
}
TEST_F(DialogTest, RemoveDefaultButton) {
// Removing buttons from the dialog here should not cause a crash on close.
delete dialog()->GetOkButton();
delete dialog()->GetCancelButton();
}
TEST_F(DialogTest, HitTest_HiddenTitle) {
// Ensure that BubbleFrameView hit-tests as expected when the title is hidden.
const NonClientView* view = dialog()->GetWidget()->non_client_view();
BubbleFrameView* frame = static_cast<BubbleFrameView*>(view->frame_view());
constexpr struct {
const int point;
const int hit;
} kCases[] = {
{0, HTTRANSPARENT},
{10, HTCAPTION},
{20, HTNOWHERE},
{50, HTCLIENT /* Space is reserved for the close button. */},
{60, HTCLIENT},
{1000, HTNOWHERE},
};
for (const auto test_case : kCases) {
gfx::Point point(test_case.point, test_case.point);
EXPECT_EQ(test_case.hit, frame->NonClientHitTest(point))
<< " at point " << test_case.point;
}
}
TEST_F(DialogTest, HitTest_HiddenTitleNoCloseButton) {
InitializeDialog();
dialog()->set_show_close_button(false);
ShowDialog();
const NonClientView* view = dialog()->GetWidget()->non_client_view();
BubbleFrameView* frame = static_cast<BubbleFrameView*>(view->frame_view());
constexpr struct {
const int point;
const int hit;
} kCases[] = {
{0, HTTRANSPARENT}, {10, HTCAPTION}, {20, HTCLIENT},
{50, HTCLIENT}, {60, HTCLIENT}, {1000, HTNOWHERE},
};
for (const auto test_case : kCases) {
gfx::Point point(test_case.point, test_case.point);
EXPECT_EQ(test_case.hit, frame->NonClientHitTest(point))
<< " at point " << test_case.point;
}
}
TEST_F(DialogTest, HitTest_WithTitle) {
// Ensure that BubbleFrameView hit-tests as expected when the title is shown
// and the modal type is something other than not modal.
const NonClientView* view = dialog()->GetWidget()->non_client_view();
dialog()->set_title(u"Title");
dialog()->GetWidget()->UpdateWindowTitle();
dialog()->GetWidget()->LayoutRootViewIfNecessary();
BubbleFrameView* frame = static_cast<BubbleFrameView*>(view->frame_view());
constexpr struct {
const int point;
const int hit;
} kCases[] = {
{0, HTTRANSPARENT}, {10, HTCAPTION}, {20, HTCAPTION},
{50, HTCLIENT}, {60, HTCLIENT}, {1000, HTNOWHERE},
};
for (const auto test_case : kCases) {
gfx::Point point(test_case.point, test_case.point);
EXPECT_EQ(test_case.hit, frame->NonClientHitTest(point))
<< " at point " << test_case.point;
}
}
TEST_F(DialogTest, HitTest_CloseButton) {
const NonClientView* view = dialog()->GetWidget()->non_client_view();
dialog()->set_show_close_button(true);
BubbleFrameView* frame = static_cast<BubbleFrameView*>(view->frame_view());
frame->ResetWindowControls();
const gfx::Rect close_button_bounds =
frame->GetCloseButtonForTesting()->bounds();
#if BUILDFLAG(IS_WIN)
// On Win, when HTCLOSE is returned, the tooltip is automatically generated.
// Do not return |HTCLOSE| to use views tooltip.
EXPECT_EQ(HTCAPTION,
frame->NonClientHitTest(gfx::Point(close_button_bounds.x() + 4,
close_button_bounds.y() + 4)));
#else
EXPECT_EQ(HTCLOSE,
frame->NonClientHitTest(gfx::Point(close_button_bounds.x() + 4,
close_button_bounds.y() + 4)));
#endif
}
TEST_F(DialogTest, BoundsAccommodateTitle) {
TestDialog* dialog2(new TestDialog());
dialog2->set_title(u"Title");
CreateDialogWidget(dialog2);
// Remove the close button so it doesn't influence the bounds if it's taller
// than the title.
dialog()->set_show_close_button(false);
dialog2->set_show_close_button(false);
dialog()->GetWidget()->non_client_view()->ResetWindowControls();
dialog2->GetWidget()->non_client_view()->ResetWindowControls();
EXPECT_FALSE(dialog()->ShouldShowWindowTitle());
EXPECT_TRUE(dialog2->ShouldShowWindowTitle());
// Titled dialogs have taller initial frame bounds than untitled dialogs.
View* frame1 = dialog()->GetWidget()->non_client_view()->frame_view();
View* frame2 = dialog2->GetWidget()->non_client_view()->frame_view();
EXPECT_LT(frame1->GetPreferredSize().height(),
frame2->GetPreferredSize().height());
// Giving the default test dialog a title will yield the same bounds.
dialog()->set_title(u"Title");
EXPECT_TRUE(dialog()->ShouldShowWindowTitle());
dialog()->GetWidget()->UpdateWindowTitle();
EXPECT_EQ(frame1->GetPreferredSize().height(),
frame2->GetPreferredSize().height());
dialog2->TearDown();
}
TEST_F(DialogTest, ActualBoundsMatchPreferredBounds) {
dialog()->set_title(
u"La la la look at me I'm a really really long title that needs to be "
u"really really long so that the title will multiline wrap.");
dialog()->GetWidget()->UpdateWindowTitle();
views::View* root_view = dialog()->GetWidget()->GetRootView();
gfx::Size preferred_size(root_view->GetPreferredSize());
EXPECT_FALSE(preferred_size.IsEmpty());
root_view->SizeToPreferredSize();
views::test::RunScheduledLayout(root_view);
EXPECT_EQ(preferred_size, root_view->size());
}
// Tests default focus is assigned correctly when showing a new dialog.
TEST_F(DialogTest, InitialFocus) {
EXPECT_TRUE(dialog()->input()->HasFocus());
EXPECT_EQ(dialog()->input(), dialog()->GetFocusManager()->GetFocusedView());
}
// A dialog for testing initial focus with only an OK button.
class InitialFocusTestDialog : public DialogDelegateView {
public:
InitialFocusTestDialog() {
DialogDelegate::SetButtons(ui::DIALOG_BUTTON_OK);
}
InitialFocusTestDialog(const InitialFocusTestDialog&) = delete;
InitialFocusTestDialog& operator=(const InitialFocusTestDialog&) = delete;
~InitialFocusTestDialog() override = default;
};
// If the Widget can't be activated while the initial focus View is requesting
// focus, test it is still able to receive focus once the Widget is activated.
TEST_F(DialogTest, InitialFocusWithDeactivatedWidget) {
InitialFocusTestDialog* dialog = new InitialFocusTestDialog();
Widget* dialog_widget = CreateDialogWidget(dialog);
// Set the initial focus while the Widget is unactivated to prevent the
// initially focused View from receiving focus. Use a minimised state here to
// prevent the Widget from being activated while this happens.
dialog_widget->SetInitialFocus(ui::WindowShowState::SHOW_STATE_MINIMIZED);
// Nothing should be focused, because the Widget is still deactivated.
EXPECT_EQ(nullptr, dialog_widget->GetFocusManager()->GetFocusedView());
EXPECT_EQ(dialog->GetOkButton(),
dialog_widget->GetFocusManager()->GetStoredFocusView());
dialog_widget->Show();
// After activation, the initially focused View should have focus as intended.
EXPECT_EQ(dialog->GetOkButton(),
dialog_widget->GetFocusManager()->GetFocusedView());
EXPECT_TRUE(dialog->GetOkButton()->HasFocus());
dialog_widget->CloseNow();
}
// If the initially focused View provided is unfocusable, check the next
// available focusable View is focused.
TEST_F(DialogTest, UnfocusableInitialFocus) {
#if BUILDFLAG(IS_MAC)
// On Mac, make all buttons unfocusable by turning off full keyboard access.
// This is the more common configuration, and if a dialog has a focusable
// textfield, tree or table, that should obtain focus instead.
ui::test::ScopedFakeFullKeyboardAccess::GetInstance()
->set_full_keyboard_access_state(false);
#endif
DialogDelegateView* dialog = new DialogDelegateView();
Textfield* textfield = new Textfield();
dialog->AddChildView(textfield);
Widget* dialog_widget = CreateDialogWidget(dialog);
#if !BUILDFLAG(IS_MAC)
// For non-Mac, turn off focusability on all the dialog's buttons manually.
// This achieves the same effect as disabling full keyboard access.
dialog->GetOkButton()->SetFocusBehavior(View::FocusBehavior::NEVER);
dialog->GetCancelButton()->SetFocusBehavior(View::FocusBehavior::NEVER);
dialog->GetBubbleFrameView()->GetCloseButtonForTesting()->SetFocusBehavior(
View::FocusBehavior::NEVER);
#endif
// On showing the dialog, the initially focused View will be the OK button.
// Since it is no longer focusable, focus should advance to the next focusable
// View, which is |textfield|.
dialog_widget->Show();
EXPECT_TRUE(textfield->HasFocus());
EXPECT_EQ(textfield, dialog->GetFocusManager()->GetFocusedView());
dialog_widget->CloseNow();
}
TEST_F(DialogTest, ButtonEnableUpdatesState) {
test::WidgetTest::WidgetAutoclosePtr widget(
CreateDialogWidget(new DialogDelegateView));
auto* dialog = static_cast<DialogDelegateView*>(widget->widget_delegate());
EXPECT_TRUE(dialog->GetOkButton()->GetEnabled());
dialog->SetButtonEnabled(ui::DIALOG_BUTTON_OK, false);
dialog->DialogModelChanged();
EXPECT_FALSE(dialog->GetOkButton()->GetEnabled());
}
using DialogDelegateCloseTest = ViewsTestBase;
TEST_F(DialogDelegateCloseTest, AnyCallbackInhibitsDefaultClose) {
DialogDelegateView dialog;
bool cancelled = false;
bool accepted = false;
dialog.SetCancelCallback(
base::BindLambdaForTesting([&]() { cancelled = true; }));
dialog.SetAcceptCallback(
base::BindLambdaForTesting([&]() { accepted = true; }));
// At this point DefaultClose() would invoke either Accept() or Cancel().
EXPECT_TRUE(dialog.Close());
EXPECT_FALSE(cancelled);
EXPECT_FALSE(accepted);
}
TEST_F(DialogDelegateCloseTest,
RecursiveCloseFromAcceptCallbackDoesNotTriggerSecondCallback) {
DialogDelegateView dialog;
bool closed = false;
bool accepted = false;
dialog.SetCloseCallback(
base::BindLambdaForTesting([&]() { closed = true; }));
dialog.SetAcceptCallback(base::BindLambdaForTesting([&]() {
accepted = true;
dialog.Close();
}));
EXPECT_TRUE(dialog.Accept());
EXPECT_TRUE(accepted);
EXPECT_FALSE(closed);
}
class TestDialogDelegateView : public DialogDelegateView {
public:
TestDialogDelegateView(bool* accepted, bool* cancelled)
: accepted_(accepted), cancelled_(cancelled) {}
~TestDialogDelegateView() override = default;
private:
bool Accept() override {
*(accepted_) = true;
return true;
}
bool Cancel() override {
*(cancelled_) = true;
return true;
}
raw_ptr<bool> accepted_;
raw_ptr<bool> cancelled_;
};
TEST_F(DialogDelegateCloseTest, OldClosePathDoesNotDoubleClose) {
bool accepted = false;
bool cancelled = false;
auto* dialog = new TestDialogDelegateView(&accepted, &cancelled);
Widget* widget =
DialogDelegate::CreateDialogWidget(dialog, GetContext(), nullptr);
widget->Show();
views::test::WidgetDestroyedWaiter destroyed_waiter(widget);
dialog->AcceptDialog();
destroyed_waiter.Wait();
EXPECT_TRUE(accepted);
EXPECT_FALSE(cancelled);
}
TEST_F(DialogDelegateCloseTest, CloseParentWidgetDoesNotInvokeCloseCallback) {
auto* dialog = new DialogDelegateView();
std::unique_ptr<Widget> parent = CreateTestWidget();
Widget* widget = DialogDelegate::CreateDialogWidget(dialog, GetContext(),
parent->GetNativeView());
bool closed = false;
dialog->SetCloseCallback(
base::BindLambdaForTesting([&closed]() { closed = true; }));
views::test::WidgetDestroyedWaiter parent_waiter(parent.get());
views::test::WidgetDestroyedWaiter dialog_waiter(widget);
parent->Close();
parent_waiter.Wait();
dialog_waiter.Wait();
EXPECT_FALSE(closed);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/window/dialog_delegate_unittest.cc | C++ | unknown | 19,562 |
// 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_WINDOW_DIALOG_OBSERVER_H_
#define UI_VIEWS_WINDOW_DIALOG_OBSERVER_H_
#include "ui/views/views_export.h"
namespace views {
// Allows properties on a DialogDelegate to be observed.
class VIEWS_EXPORT DialogObserver {
public:
// Invoked when a dialog signals a model change. E.g., the enabled buttons, or
// the button titles.
virtual void OnDialogChanged() = 0;
};
} // namespace views
#endif // UI_VIEWS_WINDOW_DIALOG_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/window/dialog_observer.h | C++ | unknown | 604 |
// 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/window/frame_background.h"
#include <algorithm>
#include "build/build_config.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/gfx/canvas.h"
#include "ui/native_theme/native_theme.h"
#include "ui/views/buildflags.h"
#include "ui/views/view.h"
namespace views {
FrameBackground::FrameBackground() = default;
FrameBackground::~FrameBackground() = default;
void FrameBackground::SetSideImages(const gfx::ImageSkia* left,
const gfx::ImageSkia* top,
const gfx::ImageSkia* right,
const gfx::ImageSkia* bottom) {
left_edge_ = left;
top_edge_ = top;
right_edge_ = right;
bottom_edge_ = bottom;
}
void FrameBackground::SetCornerImages(const gfx::ImageSkia* top_left,
const gfx::ImageSkia* top_right,
const gfx::ImageSkia* bottom_left,
const gfx::ImageSkia* bottom_right) {
top_left_corner_ = top_left;
top_right_corner_ = top_right;
bottom_left_corner_ = bottom_left;
bottom_right_corner_ = bottom_right;
}
void FrameBackground::PaintRestored(gfx::Canvas* canvas,
const View* view) const {
// Restored window painting is a superset of maximized window painting; let
// the maximized code paint the frame color and images.
PaintMaximized(canvas, view);
// Fill the frame borders with the frame color before drawing the edge images.
FillFrameBorders(canvas, view, left_edge_->width(), right_edge_->width(),
bottom_edge_->height());
// Draw the top corners and edge, scaling the corner images down if they
// are too big and relative to the vertical space available.
int top_left_height =
std::min(top_left_corner_->height(),
view->height() - bottom_left_corner_->height());
canvas->DrawImageInt(*top_left_corner_, 0, 0, top_left_corner_->width(),
top_left_height, 0, 0, top_left_corner_->width(),
top_left_height, false);
canvas->TileImageInt(
*top_edge_, top_left_corner_->width(), 0,
view->width() - top_left_corner_->width() - top_right_corner_->width(),
top_edge_->height());
int top_right_height =
std::min(top_right_corner_->height(),
view->height() - bottom_right_corner_->height());
canvas->DrawImageInt(*top_right_corner_, 0, 0, top_right_corner_->width(),
top_right_height,
view->width() - top_right_corner_->width(), 0,
top_right_corner_->width(), top_right_height, false);
// Right edge.
int right_edge_height =
view->height() - top_right_height - bottom_right_corner_->height();
canvas->TileImageInt(*right_edge_, view->width() - right_edge_->width(),
top_right_height, right_edge_->width(),
right_edge_height);
// Bottom corners and edge.
canvas->DrawImageInt(*bottom_right_corner_,
view->width() - bottom_right_corner_->width(),
view->height() - bottom_right_corner_->height());
canvas->TileImageInt(*bottom_edge_, bottom_left_corner_->width(),
view->height() - bottom_edge_->height(),
view->width() - bottom_left_corner_->width() -
bottom_right_corner_->width(),
bottom_edge_->height());
canvas->DrawImageInt(*bottom_left_corner_, 0,
view->height() - bottom_left_corner_->height());
// Left edge.
int left_edge_height =
view->height() - top_left_height - bottom_left_corner_->height();
canvas->TileImageInt(*left_edge_, 0, top_left_height, left_edge_->width(),
left_edge_height);
}
void FrameBackground::PaintMaximized(gfx::Canvas* canvas,
const View* view) const {
PaintMaximized(canvas, view->GetNativeTheme(), view->GetColorProvider(),
view->x(), view->y(), view->width());
}
void FrameBackground::PaintMaximized(gfx::Canvas* canvas,
const ui::NativeTheme* native_theme,
const ui::ColorProvider* color_provider,
int x,
int y,
int width) const {
// Fill the top with the frame color first so we have a constant background
// for areas not covered by the theme image.
#if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && \
BUILDFLAG(ENABLE_DESKTOP_AURA)
ui::NativeTheme::ExtraParams params;
params.frame_top_area.use_custom_frame = use_custom_frame_;
params.frame_top_area.is_active = is_active_;
params.frame_top_area.default_background_color = frame_color_;
native_theme->Paint(canvas->sk_canvas(), color_provider,
ui::NativeTheme::kFrameTopArea, ui::NativeTheme::kNormal,
gfx::Rect(x, y, width, top_area_height_), params);
#else
canvas->FillRect(gfx::Rect(x, y, width, top_area_height_), frame_color_);
#endif
// Draw the theme frame and overlay, if available.
if (!theme_image_.isNull()) {
canvas->TileImageInt(theme_image_, 0, theme_image_y_inset_, x, y, width,
top_area_height_, 1.0f, SkTileMode::kRepeat,
SkTileMode::kMirror);
}
if (!theme_overlay_image_.isNull())
canvas->DrawImageInt(theme_overlay_image_, x, y - maximized_top_inset_);
}
void FrameBackground::FillFrameBorders(gfx::Canvas* canvas,
const View* view,
int left_edge_width,
int right_edge_width,
int bottom_edge_height) const {
// If the window is very short, we don't need to fill any borders.
int remaining_height = view->height() - top_area_height_;
if (remaining_height <= 0)
return;
// Fill down the sides.
canvas->FillRect(
gfx::Rect(0, top_area_height_, left_edge_width, remaining_height),
frame_color_);
canvas->FillRect(gfx::Rect(view->width() - right_edge_width, top_area_height_,
right_edge_width, remaining_height),
frame_color_);
// If the window is very narrow, we're done.
int center_width = view->width() - left_edge_width - right_edge_width;
if (center_width <= 0)
return;
// Fill the bottom area.
canvas->FillRect(
gfx::Rect(left_edge_width, view->height() - bottom_edge_height,
center_width, bottom_edge_height),
frame_color_);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/window/frame_background.cc | C++ | unknown | 7,003 |
// 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_WINDOW_FRAME_BACKGROUND_H_
#define UI_VIEWS_WINDOW_FRAME_BACKGROUND_H_
#include "base/memory/raw_ptr.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/views/views_export.h"
namespace gfx {
class Canvas;
}
namespace ui {
class ColorProvider;
class NativeTheme;
}
namespace views {
class View;
// FrameBackground handles painting for all the various window frames we
// support in Chrome. It intends to consolidate paint code that historically
// was copied. One frame to rule them all!
class VIEWS_EXPORT FrameBackground {
public:
FrameBackground();
FrameBackground(const FrameBackground&) = delete;
FrameBackground& operator=(const FrameBackground&) = delete;
~FrameBackground();
// Sets the color to draw under the frame images.
void set_frame_color(SkColor color) { frame_color_ = color; }
void set_use_custom_frame(bool use_custom_frame) {
use_custom_frame_ = use_custom_frame;
}
// Sets whether the frame to be drawn should have focus.
void set_is_active(bool is_active) { is_active_ = is_active; }
// Sets the theme image for the top of the window. May be null (empty).
// Memory is owned by the caller.
void set_theme_image(const gfx::ImageSkia& image) { theme_image_ = image; }
// Sets an inset into the theme image to begin painting at.
void set_theme_image_y_inset(int y_inset) { theme_image_y_inset_ = y_inset; }
// Sets an image that overlays the top window image. Usually used to add
// edge highlighting to provide the illusion of depth. May be null (empty).
// Memory is owned by the caller.
void set_theme_overlay_image(const gfx::ImageSkia& image) {
theme_overlay_image_ = image;
}
// Sets the height of the top area to fill with the default frame color,
// which must extend behind the tab strip.
void set_top_area_height(int height) { top_area_height_ = height; }
// Vertical inset for theme image when drawing maximized.
void set_maximized_top_inset(int inset) { maximized_top_inset_ = inset; }
// Sets images used when drawing the sides of the frame.
// Caller owns the memory.
void SetSideImages(const gfx::ImageSkia* left,
const gfx::ImageSkia* top,
const gfx::ImageSkia* right,
const gfx::ImageSkia* bottom);
// Sets images used when drawing the corners of the frame.
// Caller owns the memory.
void SetCornerImages(const gfx::ImageSkia* top_left,
const gfx::ImageSkia* top_right,
const gfx::ImageSkia* bottom_left,
const gfx::ImageSkia* bottom_right);
// Paints the border for a standard, non-maximized window. Also paints the
// background of the title bar area, since the top frame border and the
// title bar background are a contiguous component.
void PaintRestored(gfx::Canvas* canvas, const View* view) const;
// Paints the border for a maximized window, which does not include the
// window edges.
void PaintMaximized(gfx::Canvas* canvas, const View* view) const;
void PaintMaximized(gfx::Canvas* canvas,
const ui::NativeTheme* native_theme,
const ui::ColorProvider* color_provider,
int x,
int y,
int width) const;
// Fills the frame side and bottom borders with the frame color.
void FillFrameBorders(gfx::Canvas* canvas,
const View* view,
int left_edge_width,
int right_edge_width,
int bottom_edge_height) const;
private:
SkColor frame_color_ = 0;
bool use_custom_frame_ = true;
bool is_active_ = true;
gfx::ImageSkia theme_image_;
int theme_image_y_inset_ = 0;
gfx::ImageSkia theme_overlay_image_;
int top_area_height_ = 0;
// Images for the sides of the frame.
raw_ptr<const gfx::ImageSkia> left_edge_ = nullptr;
raw_ptr<const gfx::ImageSkia> top_edge_ = nullptr;
raw_ptr<const gfx::ImageSkia> right_edge_ = nullptr;
raw_ptr<const gfx::ImageSkia> bottom_edge_ = nullptr;
// Images for the corners of the frame.
raw_ptr<const gfx::ImageSkia> top_left_corner_ = nullptr;
raw_ptr<const gfx::ImageSkia> top_right_corner_ = nullptr;
raw_ptr<const gfx::ImageSkia> bottom_left_corner_ = nullptr;
raw_ptr<const gfx::ImageSkia> bottom_right_corner_ = nullptr;
// Vertical inset for theme image when drawing maximized.
int maximized_top_inset_ = 0;
};
} // namespace views
#endif // UI_VIEWS_WINDOW_FRAME_BACKGROUND_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/window/frame_background.h | C++ | unknown | 4,761 |
// 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_WINDOW_FRAME_BUTTONS_H_
#define UI_VIEWS_WINDOW_FRAME_BUTTONS_H_
namespace views {
// Identifies what a button in a window frame is.
enum class FrameButton { kMinimize, kMaximize, kClose };
} // namespace views
#endif // UI_VIEWS_WINDOW_FRAME_BUTTONS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/window/frame_buttons.h | C++ | unknown | 421 |
// 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/window/frame_caption_button.h"
#include <memory>
#include <utility>
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "cc/paint/paint_flags.h"
#include "ui/base/hit_test.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/gfx/animation/slide_animation.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/rrect_f.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/views/animation/flood_fill_ink_drop_ripple.h"
#include "ui/views/animation/ink_drop.h"
#include "ui/views/animation/ink_drop_highlight.h"
#include "ui/views/animation/ink_drop_impl.h"
#include "ui/views/animation/ink_drop_ripple.h"
#include "ui/views/controls/highlight_path_generator.h"
#include "ui/views/window/hit_test_utils.h"
namespace views {
namespace {
// Ink drop parameters.
constexpr float kInkDropVisibleOpacity = 0.06f;
// The duration of the fade out animation of the old icon during a crossfade
// animation as a ratio of the duration of |swap_images_animation_|.
constexpr float kFadeOutRatio = 0.5f;
// The ratio applied to the button's alpha when the button is disabled.
constexpr float kDisabledButtonAlphaRatio = 0.5f;
} // namespace
// Custom highlight path generator for clipping ink drops and drawing focus
// rings.
class FrameCaptionButton::HighlightPathGenerator
: public views::HighlightPathGenerator {
public:
explicit HighlightPathGenerator(FrameCaptionButton* frame_caption_button)
: frame_caption_button_(frame_caption_button) {}
HighlightPathGenerator(const HighlightPathGenerator&) = delete;
HighlightPathGenerator& operator=(const HighlightPathGenerator&) = delete;
~HighlightPathGenerator() override = default;
// views::HighlightPathGenerator:
absl::optional<gfx::RRectF> GetRoundRect(const gfx::RectF& rect) override {
gfx::Rect bounds = gfx::ToRoundedRect(rect);
bounds.Inset(frame_caption_button_->GetInkdropInsets(bounds.size()));
return gfx::RRectF(gfx::RectF(bounds),
frame_caption_button_->GetInkDropCornerRadius());
}
private:
const raw_ptr<FrameCaptionButton> frame_caption_button_;
};
FrameCaptionButton::FrameCaptionButton(PressedCallback callback,
CaptionButtonIcon icon,
int hit_test_type)
: Button(std::move(callback)),
icon_(icon),
swap_images_animation_(std::make_unique<gfx::SlideAnimation>(this)) {
views::SetHitTestComponent(this, hit_test_type);
// Not focusable by default, only for accessibility.
SetFocusBehavior(FocusBehavior::ACCESSIBLE_ONLY);
SetAnimateOnStateChange(true);
swap_images_animation_->Reset(1);
SetHasInkDropActionOnClick(true);
InkDrop::Get(this)->SetMode(views::InkDropHost::InkDropMode::ON);
InkDrop::Get(this)->SetVisibleOpacity(kInkDropVisibleOpacity);
UpdateInkDropBaseColor();
InkDrop::UseInkDropWithoutAutoHighlight(InkDrop::Get(this),
/*highlight_on_hover=*/false);
InkDrop::Get(this)->SetCreateRippleCallback(base::BindRepeating(
[](FrameCaptionButton* host) -> std::unique_ptr<views::InkDropRipple> {
return std::make_unique<views::FloodFillInkDropRipple>(
InkDrop::Get(host), host->size(),
host->GetInkdropInsets(host->size()),
InkDrop::Get(host)->GetInkDropCenterBasedOnLastEvent(),
InkDrop::Get(host)->GetBaseColor(),
InkDrop::Get(host)->GetVisibleOpacity());
},
this));
views::HighlightPathGenerator::Install(
this, std::make_unique<HighlightPathGenerator>(this));
// Do not flip the gfx::Canvas passed to the OnPaint() method. The snap left
// and snap right button icons should not be flipped. The other icons are
// horizontally symmetrical.
}
FrameCaptionButton::~FrameCaptionButton() = default;
// static
SkColor FrameCaptionButton::GetButtonColor(SkColor background_color) {
// Use IsDark() to change target colors instead of PickContrastingColor(), so
// that DefaultFrameHeader::GetTitleColor() (which uses different target
// colors) can change between light/dark targets at the same time. It looks
// bad when the title and caption buttons disagree about whether to be light
// or dark.
const SkColor default_foreground = color_utils::IsDark(background_color)
? gfx::kGoogleGrey200
: gfx::kGoogleGrey700;
const SkColor high_contrast_foreground =
color_utils::GetColorWithMaxContrast(background_color);
return color_utils::BlendForMinContrast(
default_foreground, background_color, high_contrast_foreground,
color_utils::kMinimumVisibleContrastRatio)
.color;
}
// static
float FrameCaptionButton::GetInactiveButtonColorAlphaRatio() {
return 0.38f;
}
void FrameCaptionButton::SetImage(CaptionButtonIcon icon,
Animate animate,
const gfx::VectorIcon& icon_definition) {
gfx::ImageSkia new_icon_image =
gfx::CreateVectorIcon(icon_definition, GetButtonColor(background_color_));
// The early return is dependent on |animate| because callers use SetImage()
// with Animate::kNo to progress the crossfade animation to the end.
if (icon == icon_ &&
(animate == Animate::kYes || !swap_images_animation_->is_animating()) &&
new_icon_image.BackedBySameObjectAs(icon_image_)) {
return;
}
if (animate == Animate::kYes)
crossfade_icon_image_ = icon_image_;
icon_ = icon;
icon_definition_ = &icon_definition;
icon_image_ = new_icon_image;
if (animate == Animate::kYes) {
swap_images_animation_->Reset(0);
swap_images_animation_->SetSlideDuration(base::Milliseconds(200));
swap_images_animation_->Show();
} else {
swap_images_animation_->Reset(1);
}
SchedulePaint();
}
bool FrameCaptionButton::IsAnimatingImageSwap() const {
return swap_images_animation_->is_animating();
}
void FrameCaptionButton::SetAlpha(SkAlpha alpha) {
if (alpha_ != alpha) {
alpha_ = alpha;
SchedulePaint();
}
}
void FrameCaptionButton::OnGestureEvent(ui::GestureEvent* event) {
// Button does not become pressed when the user drags off and then back
// onto the button. Make FrameCaptionButton pressed in this case because this
// behavior is more consistent with AlternateFrameSizeButton.
if (event->type() == ui::ET_GESTURE_SCROLL_BEGIN ||
event->type() == ui::ET_GESTURE_SCROLL_UPDATE) {
if (HitTestPoint(event->location())) {
SetState(STATE_PRESSED);
RequestFocus();
event->StopPropagation();
} else {
SetState(STATE_NORMAL);
}
} else if (event->type() == ui::ET_GESTURE_SCROLL_END) {
if (HitTestPoint(event->location())) {
SetState(STATE_HOVERED);
NotifyClick(*event);
event->StopPropagation();
}
}
if (!event->handled())
Button::OnGestureEvent(event);
}
views::PaintInfo::ScaleType FrameCaptionButton::GetPaintScaleType() const {
return views::PaintInfo::ScaleType::kUniformScaling;
}
void FrameCaptionButton::SetBackgroundColor(SkColor background_color) {
if (background_color_ == background_color)
return;
background_color_ = background_color;
// Refresh the icon since the color may have changed.
if (icon_definition_)
SetImage(icon_, Animate::kNo, *icon_definition_);
UpdateInkDropBaseColor();
OnPropertyChanged(&background_color_, kPropertyEffectsPaint);
}
SkColor FrameCaptionButton::GetBackgroundColor() const {
return background_color_;
}
void FrameCaptionButton::SetInkDropCornerRadius(int ink_drop_corner_radius) {
ink_drop_corner_radius_ = ink_drop_corner_radius;
// Changes to |ink_drop_corner_radius| will affect the ink drop. Therefore
// this effect is handled by the ink drop.
OnPropertyChanged(&ink_drop_corner_radius_, kPropertyEffectsNone);
}
int FrameCaptionButton::GetInkDropCornerRadius() const {
return ink_drop_corner_radius_;
}
base::CallbackListSubscription
FrameCaptionButton::AddBackgroundColorChangedCallback(
PropertyChangedCallback callback) {
return AddPropertyChangedCallback(&background_color_, callback);
}
void FrameCaptionButton::SetPaintAsActive(bool paint_as_active) {
if (paint_as_active == paint_as_active_)
return;
paint_as_active_ = paint_as_active;
OnPropertyChanged(&paint_as_active_, kPropertyEffectsPaint);
}
bool FrameCaptionButton::GetPaintAsActive() const {
return paint_as_active_;
}
void FrameCaptionButton::DrawHighlight(gfx::Canvas* canvas,
cc::PaintFlags flags) {
const gfx::Point center(GetMirroredRect(GetContentsBounds()).CenterPoint());
canvas->DrawCircle(center, ink_drop_corner_radius_, flags);
}
void FrameCaptionButton::DrawIconContents(gfx::Canvas* canvas,
gfx::ImageSkia image,
int x,
int y,
cc::PaintFlags flags) {
canvas->DrawImageInt(image, x, y, flags);
}
gfx::Size FrameCaptionButton::GetInkDropSize() const {
return gfx::Size(2 * GetInkDropCornerRadius(), 2 * GetInkDropCornerRadius());
}
gfx::Insets FrameCaptionButton::GetInkdropInsets(
const gfx::Size& button_size) const {
return gfx::Insets::VH((button_size.height() - GetInkDropSize().height()) / 2,
(button_size.width() - GetInkDropSize().width()) / 2);
}
void FrameCaptionButton::PaintButtonContents(gfx::Canvas* canvas) {
constexpr SkAlpha kHighlightVisibleOpacity = 0x14;
SkAlpha highlight_alpha = SK_AlphaTRANSPARENT;
if (hover_animation().is_animating()) {
highlight_alpha =
static_cast<SkAlpha>(hover_animation().CurrentValueBetween(
SK_AlphaTRANSPARENT, kHighlightVisibleOpacity));
} else if (GetState() == STATE_HOVERED || GetState() == STATE_PRESSED) {
// Painting a circular highlight in both "hovered" and "pressed" states
// simulates and ink drop highlight mode of
// AutoHighlightMode::SHOW_ON_RIPPLE.
highlight_alpha = kHighlightVisibleOpacity;
}
if (highlight_alpha != SK_AlphaTRANSPARENT) {
// We paint the highlight manually here rather than relying on the ink drop
// highlight as it doesn't work well when the button size is changing while
// the window is moving as a result of the animation from normal to
// maximized state or vice versa. https://crbug.com/840901.
cc::PaintFlags flags;
flags.setColor(InkDrop::Get(this)->GetBaseColor());
flags.setAlphaf(highlight_alpha / 255.0f);
DrawHighlight(canvas, flags);
}
SkAlpha icon_alpha =
static_cast<SkAlpha>(swap_images_animation_->CurrentValueBetween(
SK_AlphaTRANSPARENT, SK_AlphaOPAQUE));
SkAlpha crossfade_icon_alpha = 0;
if (icon_alpha < base::ClampRound<SkAlpha>(kFadeOutRatio * SK_AlphaOPAQUE)) {
crossfade_icon_alpha =
base::ClampRound<SkAlpha>(SK_AlphaOPAQUE - icon_alpha / kFadeOutRatio);
}
gfx::Rect icon_bounds = GetContentsBounds();
icon_bounds.ClampToCenteredSize(icon_image_.size());
const int icon_bounds_x = icon_bounds.x();
const int icon_bounds_y = icon_bounds.y();
if (crossfade_icon_alpha > 0 && !crossfade_icon_image_.isNull()) {
canvas->SaveLayerAlpha(GetAlphaForIcon(alpha_));
cc::PaintFlags flags;
flags.setAlphaf(icon_alpha / 255.0f);
DrawIconContents(canvas, icon_image_, icon_bounds_x, icon_bounds_y, flags);
flags.setAlphaf(crossfade_icon_alpha / 255.0f);
flags.setBlendMode(SkBlendMode::kPlus);
DrawIconContents(canvas, crossfade_icon_image_, icon_bounds_x,
icon_bounds_y, flags);
canvas->Restore();
} else {
if (!swap_images_animation_->is_animating())
icon_alpha = alpha_;
cc::PaintFlags flags;
flags.setAlphaf(GetAlphaForIcon(icon_alpha) / 255.0f);
DrawIconContents(canvas, icon_image_, icon_bounds_x, icon_bounds_y, flags);
}
}
SkAlpha FrameCaptionButton::GetAlphaForIcon(SkAlpha base_alpha) const {
if (!GetEnabled())
return base::ClampRound<SkAlpha>(base_alpha * kDisabledButtonAlphaRatio);
if (paint_as_active_)
return base_alpha;
// Paint icons as active when they are hovered over or pressed.
double inactive_alpha = GetInactiveButtonColorAlphaRatio();
if (hover_animation().is_animating()) {
inactive_alpha =
hover_animation().CurrentValueBetween(inactive_alpha, 1.0f);
} else if (GetState() == STATE_PRESSED || GetState() == STATE_HOVERED) {
inactive_alpha = 1.0f;
}
return base::ClampRound<SkAlpha>(base_alpha * inactive_alpha);
}
void FrameCaptionButton::UpdateInkDropBaseColor() {
using color_utils::GetColorWithMaxContrast;
// A typical implementation would simply do
// GetColorWithMaxContrast(background_color_). However, this could look odd
// if we use a light button glyph and dark ink drop or vice versa. So
// instead, use the lightest/darkest color in the same direction as the button
// glyph color.
// TODO(pkasting): It would likely be better to make the button glyph always
// be an alpha-blended version of GetColorWithMaxContrast(background_color_).
const SkColor button_color = GetButtonColor(background_color_);
InkDrop::Get(this)->SetBaseColor(
GetColorWithMaxContrast(GetColorWithMaxContrast(button_color)));
}
BEGIN_METADATA(FrameCaptionButton, Button)
ADD_PROPERTY_METADATA(SkColor, BackgroundColor, ui::metadata::SkColorConverter)
ADD_PROPERTY_METADATA(int, InkDropCornerRadius)
ADD_READONLY_PROPERTY_METADATA(CaptionButtonIcon, Icon)
ADD_PROPERTY_METADATA(bool, PaintAsActive)
END_METADATA
} // namespace views
DEFINE_ENUM_CONVERTERS(
views::CaptionButtonIcon,
{views::CaptionButtonIcon::CAPTION_BUTTON_ICON_MINIMIZE,
u"CAPTION_BUTTON_ICON_MINIMIZE"},
{views::CaptionButtonIcon::CAPTION_BUTTON_ICON_MAXIMIZE_RESTORE,
u"CAPTION_BUTTON_ICON_MAXIMIZE_RESTORE"},
{views::CaptionButtonIcon::CAPTION_BUTTON_ICON_CLOSE,
u"CAPTION_BUTTON_ICON_CLOSE"},
{views::CaptionButtonIcon::CAPTION_BUTTON_ICON_LEFT_TOP_SNAPPED,
u"CAPTION_BUTTON_ICON_LEFT_TOP_SNAPPED"},
{views::CaptionButtonIcon::CAPTION_BUTTON_ICON_RIGHT_BOTTOM_SNAPPED,
u"CAPTION_BUTTON_ICON_RIGHT_BOTTOM_SNAPPED"},
{views::CaptionButtonIcon::CAPTION_BUTTON_ICON_BACK,
u"CAPTION_BUTTON_ICON_BACK"},
{views::CaptionButtonIcon::CAPTION_BUTTON_ICON_LOCATION,
u"CAPTION_BUTTON_ICON_LOCATION"},
{views::CaptionButtonIcon::CAPTION_BUTTON_ICON_MENU,
u"CAPTION_BUTTON_ICON_MENU"},
{views::CaptionButtonIcon::CAPTION_BUTTON_ICON_ZOOM,
u"CAPTION_BUTTON_ICON_ZOOM"},
{views::CaptionButtonIcon::CAPTION_BUTTON_ICON_CENTER,
u"CAPTION_BUTTON_ICON_CENTER"},
{views::CaptionButtonIcon::CAPTION_BUTTON_ICON_FLOAT,
u"CAPTION_BUTTON_ICON_FLOAT"},
{views::CaptionButtonIcon::CAPTION_BUTTON_ICON_CUSTOM,
u"CAPTION_BUTTON_ICON_CUSTOM"},
{views::CaptionButtonIcon::CAPTION_BUTTON_ICON_COUNT,
u"CAPTION_BUTTON_ICON_COUNT"})
| Zhao-PengFei35/chromium_src_4 | ui/views/window/frame_caption_button.cc | C++ | unknown | 15,285 |
// 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_WINDOW_FRAME_CAPTION_BUTTON_H_
#define UI_VIEWS_WINDOW_FRAME_CAPTION_BUTTON_H_
#include <memory>
#include "base/callback_list.h"
#include "base/memory/raw_ptr.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/views_export.h"
#include "ui/views/window/caption_button_layout_constants.h"
#include "ui/views/window/caption_button_types.h"
namespace cc {
class PaintFlags;
} // namespace cc
namespace gfx {
class SlideAnimation;
struct VectorIcon;
} // namespace gfx
namespace views {
// Base class for the window caption buttons (minimize, maximize, restore,
// close).
class VIEWS_EXPORT FrameCaptionButton : public views::Button {
public:
METADATA_HEADER(FrameCaptionButton);
enum class Animate { kYes, kNo };
FrameCaptionButton(PressedCallback callback,
CaptionButtonIcon icon,
int hit_test_type);
FrameCaptionButton(const FrameCaptionButton&) = delete;
FrameCaptionButton& operator=(const FrameCaptionButton&) = delete;
~FrameCaptionButton() override;
// Gets the color to use for a frame caption button.
static SkColor GetButtonColor(SkColor background_color);
// Gets the alpha ratio for the colors of inactive frame caption buttons.
static float GetInactiveButtonColorAlphaRatio();
// Sets the image to use to paint the button. If |animate| is Animate::kYes,
// the button crossfades to the new visuals. If the image matches the one
// currently used by the button and |animate| is Animate::kNo, the crossfade
// animation is progressed to the end.
void SetImage(CaptionButtonIcon icon,
Animate animate,
const gfx::VectorIcon& icon_image);
// Returns true if the button is crossfading to new visuals set in
// SetImage().
bool IsAnimatingImageSwap() const;
// Sets the alpha to use for painting. Used to animate visibility changes.
void SetAlpha(SkAlpha alpha);
// views::Button:
void OnGestureEvent(ui::GestureEvent* event) override;
views::PaintInfo::ScaleType GetPaintScaleType() const override;
void SetBackgroundColor(SkColor background_color);
SkColor GetBackgroundColor() const;
void SetPaintAsActive(bool paint_as_active);
bool GetPaintAsActive() const;
void SetInkDropCornerRadius(int ink_drop_corner_radius);
int GetInkDropCornerRadius() const;
base::CallbackListSubscription AddBackgroundColorChangedCallback(
PropertyChangedCallback callback);
CaptionButtonIcon GetIcon() const { return icon_; }
const gfx::ImageSkia& icon_image() const { return icon_image_; }
const gfx::VectorIcon* icon_definition_for_test() const {
return icon_definition_;
}
protected:
// views::Button override:
void PaintButtonContents(gfx::Canvas* canvas) override;
virtual void DrawHighlight(gfx::Canvas* canvas, cc::PaintFlags flags);
virtual void DrawIconContents(gfx::Canvas* canvas,
gfx::ImageSkia image,
int x,
int y,
cc::PaintFlags flags);
// Returns the size of the inkdrop ripple.
virtual gfx::Size GetInkDropSize() const;
// Returns the amount by which the inkdrop ripple and mask should be insetted
// from the button size in order to draw the inkdrop with a size returned by
// GetInkDropSize().
gfx::Insets GetInkdropInsets(const gfx::Size& button_size) const;
private:
class HighlightPathGenerator;
// Determines what alpha to use for the icon based on animation and
// active state.
SkAlpha GetAlphaForIcon(SkAlpha base_alpha) const;
void UpdateInkDropBaseColor();
// The button's current icon.
CaptionButtonIcon icon_;
// The current background color.
SkColor background_color_ = gfx::kPlaceholderColor;
// Whether the button should be painted as active.
bool paint_as_active_ = false;
// Current alpha to use for painting.
SkAlpha alpha_ = SK_AlphaOPAQUE;
// Radius of the ink drop highlight and mask.
int ink_drop_corner_radius_ = kCaptionButtonInkDropDefaultCornerRadius;
// The image id (kept for the purposes of testing) and image used to paint the
// button's icon.
raw_ptr<const gfx::VectorIcon> icon_definition_ = nullptr;
gfx::ImageSkia icon_image_;
// The icon image to crossfade from.
gfx::ImageSkia crossfade_icon_image_;
// Crossfade animation started when the button's images are changed by
// SetImage().
std::unique_ptr<gfx::SlideAnimation> swap_images_animation_;
};
} // namespace views
#endif // UI_VIEWS_WINDOW_FRAME_CAPTION_BUTTON_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/window/frame_caption_button.h | C++ | unknown | 4,854 |
// 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/window/frame_caption_button.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/hit_test.h"
#include "ui/gfx/color_utils.h"
#include "ui/views/test/view_metadata_test_utils.h"
#include "ui/views/view.h"
#include "ui/views/window/caption_button_types.h"
namespace {
constexpr SkColor kBackgroundColors[] = {
SK_ColorBLACK, SK_ColorDKGRAY,
SK_ColorGRAY, SK_ColorLTGRAY,
SK_ColorWHITE, SK_ColorRED,
SK_ColorYELLOW, SK_ColorCYAN,
SK_ColorBLUE, SkColorSetRGB(230, 138, 90),
};
} // namespace
namespace views {
TEST(FrameCaptionButtonTest, ThemedColorContrast) {
for (SkColor background_color : kBackgroundColors) {
SkColor button_color = FrameCaptionButton::GetButtonColor(background_color);
EXPECT_GE(color_utils::GetContrastRatio(button_color, background_color), 3);
}
}
TEST(FrameCaptionButtonTest, DefaultAccessibilityFocus) {
FrameCaptionButton button(Button::PressedCallback(),
CAPTION_BUTTON_ICON_MINIMIZE, HTMINBUTTON);
EXPECT_EQ(View::FocusBehavior::ACCESSIBLE_ONLY, button.GetFocusBehavior());
}
TEST(FrameCaptionButtonTest, MetadataTest) {
FrameCaptionButton button(Button::PressedCallback(),
CAPTION_BUTTON_ICON_MINIMIZE, HTMINBUTTON);
test::TestViewMetadata(&button);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/window/frame_caption_button_unittest.cc | C++ | unknown | 1,542 |
// 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/window/hit_test_utils.h"
#include "ui/base/hit_test.h"
#include "ui/gfx/geometry/point.h"
#include "ui/views/view.h"
#include "ui/views/view_class_properties.h"
namespace views {
int GetHitTestComponent(View* view, const gfx::Point& point_in_widget) {
gfx::Point point_in_view(point_in_widget);
View::ConvertPointFromWidget(view, &point_in_view);
if (!view->GetLocalBounds().Contains(point_in_view))
return HTNOWHERE;
View* target_view = view->GetEventHandlerForPoint(point_in_view);
while (target_view) {
int component = target_view->GetProperty(kHitTestComponentKey);
if (component != HTNOWHERE)
return component;
if (target_view == view)
break;
target_view = target_view->parent();
}
return HTNOWHERE;
}
void SetHitTestComponent(View* view, int hit_test_id) {
view->SetProperty(kHitTestComponentKey, hit_test_id);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/window/hit_test_utils.cc | C++ | unknown | 1,060 |
// 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_WINDOW_HIT_TEST_UTILS_H_
#define UI_VIEWS_WINDOW_HIT_TEST_UTILS_H_
#include "ui/views/views_export.h"
namespace gfx {
class Point;
}
namespace views {
class View;
// Returns the inner most non-HTNOWHERE |kHitTestComponentKey| value at
// |point_in_widget| within the hierarchy of |view|, otherwise returns
// HTNOWHERE.
VIEWS_EXPORT int GetHitTestComponent(View* view,
const gfx::Point& point_in_widget);
// Sets the |kHitTestComponentKey| property of |view|.
VIEWS_EXPORT void SetHitTestComponent(View* view, int hit_test_id);
} // namespace views
#endif // UI_VIEWS_WINDOW_HIT_TEST_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/window/hit_test_utils.h | C++ | unknown | 801 |
// 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/window/hit_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/hit_test.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/view.h"
#include "ui/views/view_class_properties.h"
#include "ui/views/widget/widget.h"
namespace views {
using GetHitTestComponentTest = ViewsTestBase;
TEST_F(GetHitTestComponentTest, BasicTests) {
Widget* widget = new Widget;
widget->Init(CreateParams(Widget::InitParams::TYPE_WINDOW));
// Testing arrangement diagram:
// *=============root:HTCLIENT=============*
// | *=left:HTLEFT=* *=nowhere:HTNOWHERE=* |
// | | | | *=right:HTRIGHT=* | |
// | | | | | | | |
// | | | | *===============* | |
// | *=============* *===================* |
// *=======================================*
View* root = widget->GetRootView();
root->SetProperty(views::kHitTestComponentKey, static_cast<int>(HTCLIENT));
root->SetBounds(0, 0, 100, 100);
View* left = new View;
left->SetProperty(views::kHitTestComponentKey, static_cast<int>(HTLEFT));
left->SetBounds(10, 10, 30, 80);
root->AddChildView(left);
View* nowhere = new View;
nowhere->SetBounds(60, 10, 30, 80);
root->AddChildView(nowhere);
View* right = new View;
right->SetProperty(views::kHitTestComponentKey, static_cast<int>(HTRIGHT));
right->SetBounds(10, 10, 10, 60);
nowhere->AddChildView(right);
// Hit the root view.
EXPECT_EQ(GetHitTestComponent(root, gfx::Point(50, 50)), HTCLIENT);
// Hit the left view.
EXPECT_EQ(GetHitTestComponent(root, gfx::Point(25, 50)), HTLEFT);
// Hit the nowhere view, should return the root view's value.
EXPECT_EQ(GetHitTestComponent(root, gfx::Point(65, 50)), HTCLIENT);
// Hit the right view.
EXPECT_EQ(GetHitTestComponent(root, gfx::Point(75, 50)), HTRIGHT);
// Hit outside the root view.
EXPECT_EQ(GetHitTestComponent(root, gfx::Point(200, 50)), HTNOWHERE);
widget->CloseNow();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/window/hit_test_utils_unittest.cc | C++ | unknown | 2,146 |
// 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/window/native_frame_view.h"
#include "build/build_config.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/views/widget/native_widget.h"
#include "ui/views/widget/widget.h"
#if BUILDFLAG(IS_WIN)
#include "ui/views/win/hwnd_util.h"
#endif
namespace views {
////////////////////////////////////////////////////////////////////////////////
// NativeFrameView, public:
NativeFrameView::NativeFrameView(Widget* frame) : frame_(frame) {}
NativeFrameView::~NativeFrameView() = default;
////////////////////////////////////////////////////////////////////////////////
// NativeFrameView, NonClientFrameView overrides:
gfx::Rect NativeFrameView::GetBoundsForClientView() const {
return gfx::Rect(0, 0, width(), height());
}
gfx::Rect NativeFrameView::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
#if BUILDFLAG(IS_WIN)
return views::GetWindowBoundsForClientBounds(
static_cast<View*>(const_cast<NativeFrameView*>(this)), client_bounds);
#else
// Enforce minimum size (1, 1) in case that |client_bounds| is passed with
// empty size.
gfx::Rect window_bounds = client_bounds;
if (window_bounds.IsEmpty())
window_bounds.set_size(gfx::Size(1, 1));
return window_bounds;
#endif
}
int NativeFrameView::NonClientHitTest(const gfx::Point& point) {
return frame_->client_view()->NonClientHitTest(point);
}
void NativeFrameView::GetWindowMask(const gfx::Size& size,
SkPath* window_mask) {
// Nothing to do, we use the default window mask.
}
void NativeFrameView::ResetWindowControls() {
// Nothing to do.
}
void NativeFrameView::UpdateWindowIcon() {
// Nothing to do.
}
void NativeFrameView::UpdateWindowTitle() {
// Nothing to do.
}
void NativeFrameView::SizeConstraintsChanged() {
// Nothing to do.
}
gfx::Size NativeFrameView::CalculatePreferredSize() const {
gfx::Size client_preferred_size = frame_->client_view()->GetPreferredSize();
#if BUILDFLAG(IS_WIN)
// Returns the client size. On Windows, this is the expected behavior for
// native frames (see |NativeWidgetWin::WidgetSizeIsClientSize()|), while
// other platforms currently always return client bounds from
// |GetWindowBoundsForClientBounds()|.
return client_preferred_size;
#else
return frame_->non_client_view()
->GetWindowBoundsForClientBounds(gfx::Rect(client_preferred_size))
.size();
#endif
}
gfx::Size NativeFrameView::GetMinimumSize() const {
return frame_->client_view()->GetMinimumSize();
}
gfx::Size NativeFrameView::GetMaximumSize() const {
return frame_->client_view()->GetMaximumSize();
}
BEGIN_METADATA(NativeFrameView, NonClientFrameView)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/window/native_frame_view.cc | C++ | unknown | 2,869 |
// 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_WINDOW_NATIVE_FRAME_VIEW_H_
#define UI_VIEWS_WINDOW_NATIVE_FRAME_VIEW_H_
#include "base/memory/raw_ptr.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/views/metadata/view_factory.h"
#include "ui/views/window/non_client_view.h"
namespace views {
class Widget;
class VIEWS_EXPORT NativeFrameView : public NonClientFrameView {
public:
METADATA_HEADER(NativeFrameView);
explicit NativeFrameView(Widget* frame);
NativeFrameView(const NativeFrameView&) = delete;
NativeFrameView& operator=(const NativeFrameView&) = delete;
~NativeFrameView() override;
// NonClientFrameView overrides:
gfx::Rect GetBoundsForClientView() const override;
gfx::Rect GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const override;
int NonClientHitTest(const gfx::Point& point) override;
void GetWindowMask(const gfx::Size& size, SkPath* window_mask) override;
void ResetWindowControls() override;
void UpdateWindowIcon() override;
void UpdateWindowTitle() override;
void SizeConstraintsChanged() override;
// View overrides:
gfx::Size CalculatePreferredSize() const override;
gfx::Size GetMinimumSize() const override;
gfx::Size GetMaximumSize() const override;
private:
// Our containing frame.
raw_ptr<Widget> frame_;
};
BEGIN_VIEW_BUILDER(VIEWS_EXPORT, NativeFrameView, NonClientFrameView)
END_VIEW_BUILDER
} // namespace views
DEFINE_VIEW_BUILDER(VIEWS_EXPORT, NativeFrameView)
#endif // UI_VIEWS_WINDOW_NATIVE_FRAME_VIEW_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/window/native_frame_view.h | C++ | unknown | 1,662 |
// 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_WINDOW_NATIVE_FRAME_VIEW_MAC_H_
#define UI_VIEWS_WINDOW_NATIVE_FRAME_VIEW_MAC_H_
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/views/window/native_frame_view.h"
namespace views {
class Widget;
class VIEWS_EXPORT NativeFrameViewMac : public NativeFrameView {
public:
METADATA_HEADER(NativeFrameViewMac);
explicit NativeFrameViewMac(Widget* frame);
NativeFrameViewMac(const NativeFrameViewMac&) = delete;
NativeFrameViewMac& operator=(const NativeFrameViewMac&) = delete;
~NativeFrameViewMac() override;
// NonClientFrameView
gfx::Rect GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const override;
};
} // namespace views
#endif // UI_VIEWS_WINDOW_NATIVE_FRAME_VIEW_MAC_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/window/native_frame_view_mac.h | C++ | unknown | 900 |
// 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/window/native_frame_view_mac.h"
#import <Cocoa/Cocoa.h>
#include "ui/base/metadata/metadata_impl_macros.h"
#import "ui/gfx/mac/coordinate_conversion.h"
#include "ui/views/widget/widget.h"
namespace views {
NativeFrameViewMac::NativeFrameViewMac(Widget* widget)
: NativeFrameView(widget) {}
NativeFrameViewMac::~NativeFrameViewMac() = default;
gfx::Rect NativeFrameViewMac::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
NSWindow* ns_window = GetWidget()->GetNativeWindow().GetNativeNSWindow();
gfx::Rect window_bounds = gfx::ScreenRectFromNSRect([ns_window
frameRectForContentRect:gfx::ScreenRectToNSRect(client_bounds)]);
// Enforce minimum size (1, 1) in case that |client_bounds| is passed with
// empty size.
if (window_bounds.IsEmpty())
window_bounds.set_size(gfx::Size(1, 1));
return window_bounds;
}
BEGIN_METADATA(NativeFrameViewMac, NativeFrameView)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/window/native_frame_view_mac.mm | Objective-C++ | unknown | 1,120 |
// 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/window/non_client_view.h"
#include <memory>
#include <utility>
#include "base/containers/cxx20_erase.h"
#include "build/build_config.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/hit_test.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/rect_based_targeting_utils.h"
#include "ui/views/view_targeter.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/client_view.h"
#if BUILDFLAG(IS_WIN)
#include "ui/display/win/screen_win.h"
#endif
namespace views {
NonClientFrameView::~NonClientFrameView() = default;
bool NonClientFrameView::ShouldPaintAsActive() const {
return GetWidget()->ShouldPaintAsActive();
}
int NonClientFrameView::GetHTComponentForFrame(const gfx::Point& point,
const gfx::Insets& resize_border,
int top_resize_corner_height,
int resize_corner_width,
bool can_resize) {
bool point_in_top = point.y() < resize_border.top();
bool point_in_bottom = point.y() >= height() - resize_border.bottom();
bool point_in_left = point.x() < resize_border.left();
bool point_in_right = point.x() >= width() - resize_border.right();
if (!point_in_left && !point_in_right && !point_in_top && !point_in_bottom)
return HTNOWHERE;
point_in_top |= point.y() < top_resize_corner_height;
point_in_left |= point.x() < resize_corner_width;
point_in_right |= point.x() >= width() - resize_corner_width;
int component;
if (point_in_top) {
if (point_in_left) {
component = HTTOPLEFT;
} else if (point_in_right) {
component = HTTOPRIGHT;
} else {
component = HTTOP;
}
} else if (point_in_bottom) {
if (point_in_left) {
component = HTBOTTOMLEFT;
} else if (point_in_right) {
component = HTBOTTOMRIGHT;
} else {
component = HTBOTTOM;
}
} else if (point_in_left) {
component = HTLEFT;
} else {
CHECK(point_in_right);
component = HTRIGHT;
}
// If the window can't be resized, there are no resize boundaries, just
// window borders.
return can_resize ? component : HTBORDER;
}
gfx::Rect NonClientFrameView::GetBoundsForClientView() const {
return gfx::Rect();
}
gfx::Rect NonClientFrameView::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
return client_bounds;
}
bool NonClientFrameView::GetClientMask(const gfx::Size& size,
SkPath* mask) const {
return false;
}
#if BUILDFLAG(IS_WIN)
gfx::Point NonClientFrameView::GetSystemMenuScreenPixelLocation() const {
gfx::Point point(GetMirroredXInView(GetBoundsForClientView().x()),
GetSystemMenuY());
View::ConvertPointToScreen(this, &point);
point = display::win::ScreenWin::DIPToScreenPoint(point);
// The native system menu seems to overlap the titlebar by 1 px. Match that.
return point - gfx::Vector2d(0, 1);
}
#endif
int NonClientFrameView::NonClientHitTest(const gfx::Point& point) {
return HTNOWHERE;
}
void NonClientFrameView::GetAccessibleNodeData(ui::AXNodeData* node_data) {
node_data->role = ax::mojom::Role::kClient;
}
void NonClientFrameView::OnThemeChanged() {
View::OnThemeChanged();
SchedulePaint();
}
void NonClientFrameView::Layout() {
if (GetLayoutManager())
GetLayoutManager()->Layout(this);
views::ClientView* client_view = GetWidget()->client_view();
client_view->SetBoundsRect(GetBoundsForClientView());
SkPath client_clip;
if (GetClientMask(client_view->size(), &client_clip))
client_view->SetClipPath(client_clip);
}
View::Views NonClientFrameView::GetChildrenInZOrder() {
View::Views paint_order = View::GetChildrenInZOrder();
views::ClientView* client_view =
GetWidget() ? GetWidget()->client_view() : nullptr;
// Move the client view to the beginning of the Z-order to ensure that the
// other children of the frame view draw on top of it.
if (client_view && base::Erase(paint_order, client_view))
paint_order.insert(paint_order.begin(), client_view);
return paint_order;
}
void NonClientFrameView::InsertClientView(ClientView* client_view) {
AddChildView(client_view);
}
NonClientFrameView::NonClientFrameView() {
SetEventTargeter(std::make_unique<views::ViewTargeter>(this));
}
#if BUILDFLAG(IS_WIN)
int NonClientFrameView::GetSystemMenuY() const {
return GetBoundsForClientView().y();
}
#endif
BEGIN_METADATA(NonClientFrameView, View)
END_METADATA
NonClientView::NonClientView(views::ClientView* client_view)
: client_view_(client_view) {
SetEventTargeter(std::make_unique<views::ViewTargeter>(this));
}
NonClientView::~NonClientView() {
// This value may have been reset before the window hierarchy shuts down,
// so we need to manually remove it.
RemoveChildView(frame_view_.get());
}
void NonClientView::SetFrameView(
std::unique_ptr<NonClientFrameView> frame_view) {
// If there is an existing frame view, ensure that the ClientView remains
// attached to the Widget by moving the ClientView to the new frame before
// removing the old frame from the view hierarchy.
std::unique_ptr<NonClientFrameView> old_frame_view = std::move(frame_view_);
frame_view_ = std::move(frame_view);
if (parent()) {
AddChildViewAt(frame_view_.get(), 0);
frame_view_->InsertClientView(client_view_);
}
if (old_frame_view)
RemoveChildView(old_frame_view.get());
}
void NonClientView::SetOverlayView(View* view) {
if (overlay_view_)
RemoveChildView(overlay_view_);
if (!view)
return;
overlay_view_ = view;
if (parent())
AddChildView(overlay_view_.get());
}
CloseRequestResult NonClientView::OnWindowCloseRequested() {
return client_view_->OnWindowCloseRequested();
}
void NonClientView::WindowClosing() {
client_view_->WidgetClosing();
}
void NonClientView::UpdateFrame() {
Widget* widget = GetWidget();
SetFrameView(widget->CreateNonClientFrameView());
widget->ThemeChanged();
InvalidateLayout();
SchedulePaint();
}
gfx::Rect NonClientView::GetWindowBoundsForClientBounds(
const gfx::Rect client_bounds) const {
return frame_view_->GetWindowBoundsForClientBounds(client_bounds);
}
int NonClientView::NonClientHitTest(const gfx::Point& point) {
// The NonClientFrameView is responsible for also asking the ClientView.
return frame_view_->NonClientHitTest(point);
}
void NonClientView::GetWindowMask(const gfx::Size& size, SkPath* window_mask) {
frame_view_->GetWindowMask(size, window_mask);
}
void NonClientView::ResetWindowControls() {
frame_view_->ResetWindowControls();
}
void NonClientView::UpdateWindowIcon() {
frame_view_->UpdateWindowIcon();
}
void NonClientView::UpdateWindowTitle() {
frame_view_->UpdateWindowTitle();
}
void NonClientView::SizeConstraintsChanged() {
frame_view_->SizeConstraintsChanged();
}
gfx::Size NonClientView::CalculatePreferredSize() const {
// TODO(pkasting): This should probably be made to look similar to
// GetMinimumSize() below. This will require implementing GetPreferredSize()
// better in the various frame views.
gfx::Rect client_bounds(gfx::Point(), client_view_->GetPreferredSize());
return GetWindowBoundsForClientBounds(client_bounds).size();
}
gfx::Size NonClientView::GetMinimumSize() const {
return frame_view_->GetMinimumSize();
}
gfx::Size NonClientView::GetMaximumSize() const {
return frame_view_->GetMaximumSize();
}
void NonClientView::Layout() {
// TODO(pkasting): The frame view should have the client view as a child and
// lay it out directly + set its clip path. Done correctly, this should let
// us use a FillLayout on this class that holds |frame_view_| and
// |overlay_view_|, and eliminate CalculatePreferredSize()/GetMinimumSize()/
// GetMaximumSize()/Layout(). The frame view and client view were originally
// siblings because "many Views make the assumption they are only inserted
// into a View hierarchy once" ( http://codereview.chromium.org/27317 ), but
// where that is still the case it should simply be fixed.
frame_view_->SetBoundsRect(GetLocalBounds());
if (overlay_view_)
overlay_view_->SetBoundsRect(GetLocalBounds());
}
void NonClientView::GetAccessibleNodeData(ui::AXNodeData* node_data) {
// TODO(crbug.com/1366294): Should this be pruned from the accessibility tree?
node_data->role = ax::mojom::Role::kClient;
}
View* NonClientView::GetTooltipHandlerForPoint(const gfx::Point& point) {
// The same logic as for TargetForRect() applies here.
if (frame_view_->parent() == this) {
// During the reset of the frame_view_ it's possible to be in this code
// after it's been removed from the view hierarchy but before it's been
// removed from the NonClientView.
gfx::Point point_in_child_coords(point);
View::ConvertPointToTarget(this, frame_view_.get(), &point_in_child_coords);
View* handler =
frame_view_->GetTooltipHandlerForPoint(point_in_child_coords);
if (handler)
return handler;
}
return View::GetTooltipHandlerForPoint(point);
}
void NonClientView::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
// Add our child views here as we are added to the Widget so that if we are
// subsequently resized all the parent-child relationships are established.
// TODO(pkasting): The above comment makes no sense to me. Try to eliminate
// the various setters, and create and add children directly in the
// constructor.
if (details.is_add && GetWidget() && details.child == this) {
AddChildViewAt(frame_view_.get(), 0);
frame_view_->InsertClientView(client_view_);
if (overlay_view_)
AddChildView(overlay_view_.get());
}
}
View* NonClientView::TargetForRect(View* root, const gfx::Rect& rect) {
CHECK_EQ(root, this);
if (!UsePointBasedTargeting(rect))
return ViewTargeterDelegate::TargetForRect(root, rect);
// Because of the z-ordering of our child views (the client view is positioned
// over the non-client frame view, if the client view ever overlaps the frame
// view visually (as it does for the browser window), then it will eat
// events for the window controls. We override this method here so that we can
// detect this condition and re-route the events to the non-client frame view.
// The assumption is that the frame view's implementation of HitTest will only
// return true for area not occupied by the client view.
if (frame_view_->parent() == this) {
// During the reset of the frame_view_ it's possible to be in this code
// after it's been removed from the view hierarchy but before it's been
// removed from the NonClientView.
gfx::RectF rect_in_child_coords_f(rect);
View::ConvertRectToTarget(this, frame_view_.get(), &rect_in_child_coords_f);
gfx::Rect rect_in_child_coords =
gfx::ToEnclosingRect(rect_in_child_coords_f);
if (frame_view_->HitTestRect(rect_in_child_coords))
return frame_view_->GetEventHandlerForRect(rect_in_child_coords);
}
return ViewTargeterDelegate::TargetForRect(root, rect);
}
BEGIN_METADATA(NonClientView, View)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/window/non_client_view.cc | C++ | unknown | 11,549 |
// 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_WINDOW_NON_CLIENT_VIEW_H_
#define UI_VIEWS_WINDOW_NON_CLIENT_VIEW_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/views/metadata/view_factory.h"
#include "ui/views/view.h"
#include "ui/views/view_targeter_delegate.h"
namespace views {
class ClientView;
enum class CloseRequestResult;
////////////////////////////////////////////////////////////////////////////////
// NonClientFrameView
//
// An object that subclasses NonClientFrameView is a View that renders and
// responds to events within the frame portions of the non-client area of a
// window. This view contains the ClientView (see NonClientView comments for
// details on View hierarchy).
class VIEWS_EXPORT NonClientFrameView : public View,
public ViewTargeterDelegate {
public:
METADATA_HEADER(NonClientFrameView);
enum {
// Various edges of the frame border have a 1 px shadow along their edges;
// in a few cases we shift elements based on this amount for visual appeal.
kFrameShadowThickness = 1,
// In restored mode, we draw a 1 px edge around the content area inside the
// frame border.
kClientEdgeThickness = 1,
};
NonClientFrameView();
NonClientFrameView(const NonClientFrameView&) = delete;
NonClientFrameView& operator=(const NonClientFrameView&) = delete;
~NonClientFrameView() override;
// Used to determine if the frame should be painted as active. Keyed off the
// window's actual active state and whether the widget should be rendered as
// active.
bool ShouldPaintAsActive() const;
// Helper for non-client view implementations to determine which area of the
// window border the specified |point| falls within. The other parameters are
// the size of the sizing edges, and whether or not the window can be
// resized.
int GetHTComponentForFrame(const gfx::Point& point,
const gfx::Insets& resize_border,
int top_resize_corner_height,
int resize_corner_width,
bool can_resize);
// Returns the bounds (in this View's parent's coordinates) that the client
// view should be laid out within.
virtual gfx::Rect GetBoundsForClientView() const;
virtual gfx::Rect GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const;
// Gets the clip mask (in this View's parent's coordinates) that should be
// applied to the client view. Returns false if no special clip should be
// used.
virtual bool GetClientMask(const gfx::Size& size, SkPath* mask) const;
#if BUILDFLAG(IS_WIN)
// Returns the point in screen physical coordinates at which the system menu
// should be opened.
virtual gfx::Point GetSystemMenuScreenPixelLocation() const;
#endif
// This function must ask the ClientView to do a hittest. We don't do this in
// the parent NonClientView because that makes it more difficult to calculate
// hittests for regions that are partially obscured by the ClientView, e.g.
// HTSYSMENU.
// Return value is one of the windows HT constants (see ui/base/hit_test.h).
virtual int NonClientHitTest(const gfx::Point& point);
// Used to make the hosting widget shaped (non-rectangular). For a
// rectangular window do nothing. For a shaped window update |window_mask|
// accordingly. |size| is the size of the widget.
virtual void GetWindowMask(const gfx::Size& size, SkPath* window_mask) {}
virtual void ResetWindowControls() {}
virtual void UpdateWindowIcon() {}
virtual void UpdateWindowTitle() {}
// Whether the widget can be resized or maximized has changed.
virtual void SizeConstraintsChanged() {}
// View:
void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
void OnThemeChanged() override;
void Layout() override;
Views GetChildrenInZOrder() override;
// Inserts the passed client view into this NonClientFrameView. Subclasses can
// override this method to indicate a specific insertion spot for the client
// view.
virtual void InsertClientView(ClientView* client_view);
private:
#if BUILDFLAG(IS_WIN)
// Returns the y coordinate, in local coordinates, at which the system menu
// should be opened. Since this is in DIP, it does not include the 1 px
// offset into the caption area; the caller will take care of this.
virtual int GetSystemMenuY() const;
#endif
};
////////////////////////////////////////////////////////////////////////////////
// NonClientView
//
// The NonClientView is the logical root of all Views contained within a
// Window, except for the RootView which is its parent and of which it is the
// sole child. The NonClientView has one child, the NonClientFrameView which
// is responsible for painting and responding to events from the non-client
// portions of the window, and for forwarding events to its child, the
// ClientView, which is responsible for the same for the client area of the
// window:
//
// +- views::Widget ------------------------------------+
// | +- views::RootView ------------------------------+ |
// | | +- views::NonClientView ---------------------+ | |
// | | | +- views::NonClientFrameView subclass ---+ | | |
// | | | | | | | |
// | | | | << all painting and event receiving >> | | | |
// | | | | << of the non-client areas of a >> | | | |
// | | | | << views::Widget. >> | | | |
// | | | | | | | |
// | | | | +- views::ClientView or subclass ----+ | | | |
// | | | | | | | | | |
// | | | | | << all painting and event >> | | | | |
// | | | | | << receiving of the client >> | | | | |
// | | | | | << areas of a views::Widget. >> | | | | |
// | | | | +------------------------------------+ | | | |
// | | | +----------------------------------------+ | | |
// | | +--------------------------------------------+ | |
// | +------------------------------------------------+ |
// +----------------------------------------------------+
//
class VIEWS_EXPORT NonClientView : public View, public ViewTargeterDelegate {
public:
METADATA_HEADER(NonClientView);
explicit NonClientView(ClientView* client_view);
NonClientView(const NonClientView&) = delete;
NonClientView& operator=(const NonClientView&) = delete;
~NonClientView() override;
// Returns the current NonClientFrameView instance, or NULL if
// it does not exist.
NonClientFrameView* frame_view() const { return frame_view_.get(); }
// Replaces the current NonClientFrameView (if any) with the specified one.
void SetFrameView(std::unique_ptr<NonClientFrameView> frame_view);
// Replaces the current |overlay_view_| (if any) with the specified one.
void SetOverlayView(View* view);
// Returned value signals whether the ClientView can be closed.
CloseRequestResult OnWindowCloseRequested();
// Called by the containing Window when it is closed.
void WindowClosing();
// Replaces the frame view with a new one. Used when switching window theme
// or frame style.
void UpdateFrame();
// Returns the bounds of the window required to display the content area at
// the specified bounds.
gfx::Rect GetWindowBoundsForClientBounds(const gfx::Rect client_bounds) const;
// Determines the windows HT* code when the mouse cursor is at the
// specified point, in window coordinates.
int NonClientHitTest(const gfx::Point& point);
// Returns a mask to be used to clip the top level window for the given
// size. This is used to create the non-rectangular window shape.
void GetWindowMask(const gfx::Size& size, SkPath* window_mask);
// Tells the window controls as rendered by the NonClientView to reset
// themselves to a normal state. This happens in situations where the
// containing window does not receive a normal sequences of messages that
// would lead to the controls returning to this normal state naturally, e.g.
// when the window is maximized, minimized or restored.
void ResetWindowControls();
// Tells the NonClientView to invalidate the NonClientFrameView's window icon.
void UpdateWindowIcon();
// Tells the NonClientView to invalidate the NonClientFrameView's window
// title.
void UpdateWindowTitle();
// Called when the size constraints of the window change.
void SizeConstraintsChanged();
// Get/Set client_view property.
ClientView* client_view() const { return client_view_; }
// NonClientView, View overrides:
gfx::Size CalculatePreferredSize() const override;
gfx::Size GetMinimumSize() const override;
gfx::Size GetMaximumSize() const override;
void Layout() override;
void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
views::View* GetTooltipHandlerForPoint(const gfx::Point& point) override;
protected:
// NonClientView, View overrides:
void ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) override;
private:
// ViewTargeterDelegate:
View* TargetForRect(View* root, const gfx::Rect& rect) override;
// The NonClientFrameView that renders the non-client portions of the window.
// This object is not owned by the view hierarchy because it can be replaced
// dynamically as the system settings change.
std::unique_ptr<NonClientFrameView> frame_view_;
// A ClientView object or subclass, responsible for sizing the contents view
// of the window, hit testing and perhaps other tasks depending on the
// implementation.
const raw_ptr<ClientView, DanglingUntriaged> client_view_;
// The overlay view, when non-NULL and visible, takes up the entire widget and
// is placed on top of the ClientView and NonClientFrameView.
raw_ptr<View, DanglingUntriaged> overlay_view_ = nullptr;
};
BEGIN_VIEW_BUILDER(VIEWS_EXPORT, NonClientFrameView, View)
END_VIEW_BUILDER
BEGIN_VIEW_BUILDER(VIEWS_EXPORT, NonClientView, View)
VIEW_BUILDER_VIEW_PROPERTY(NonClientFrameView, FrameView)
END_VIEW_BUILDER
} // namespace views
DEFINE_VIEW_BUILDER(VIEWS_EXPORT, NonClientFrameView)
DEFINE_VIEW_BUILDER(VIEWS_EXPORT, NonClientView)
#endif // UI_VIEWS_WINDOW_NON_CLIENT_VIEW_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/window/non_client_view.h | C++ | unknown | 10,432 |
// 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/window/window_button_order_provider.h"
namespace views {
// static
WindowButtonOrderProvider* WindowButtonOrderProvider::instance_ = nullptr;
///////////////////////////////////////////////////////////////////////////////
// WindowButtonOrderProvider, public:
// static
WindowButtonOrderProvider* WindowButtonOrderProvider::GetInstance() {
if (!instance_)
instance_ = new WindowButtonOrderProvider;
return instance_;
}
///////////////////////////////////////////////////////////////////////////////
// WindowButtonOrderProvider, protected:
WindowButtonOrderProvider::WindowButtonOrderProvider() {
trailing_buttons_.push_back(views::FrameButton::kMinimize);
trailing_buttons_.push_back(views::FrameButton::kMaximize);
trailing_buttons_.push_back(views::FrameButton::kClose);
}
WindowButtonOrderProvider::~WindowButtonOrderProvider() = default;
void WindowButtonOrderProvider::SetWindowButtonOrder(
const std::vector<views::FrameButton>& leading_buttons,
const std::vector<views::FrameButton>& trailing_buttons) {
leading_buttons_ = leading_buttons;
trailing_buttons_ = trailing_buttons;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/window/window_button_order_provider.cc | C++ | unknown | 1,308 |
// 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_WINDOW_WINDOW_BUTTON_ORDER_PROVIDER_H_
#define UI_VIEWS_WINDOW_WINDOW_BUTTON_ORDER_PROVIDER_H_
#include <vector>
#include "ui/views/views_export.h"
#include "ui/views/window/frame_buttons.h"
namespace views {
// Stores the ordering of window control buttons. Provides a default ordering
// of |kMinimize|, |FrameButton::kMaximize|, |FrameButton::kClose|, where all
// controls are on the trailing end of a window.
//
// On Linux users can provide configuration files to control the ordering. This
// configuration is checked and overrides the defaults.
class VIEWS_EXPORT WindowButtonOrderProvider {
public:
static WindowButtonOrderProvider* GetInstance();
WindowButtonOrderProvider(const WindowButtonOrderProvider&) = delete;
WindowButtonOrderProvider& operator=(const WindowButtonOrderProvider&) =
delete;
const std::vector<views::FrameButton>& leading_buttons() const {
return leading_buttons_;
}
const std::vector<views::FrameButton>& trailing_buttons() const {
return trailing_buttons_;
}
void SetWindowButtonOrder(
const std::vector<views::FrameButton>& leading_buttons,
const std::vector<views::FrameButton>& trailing_buttons);
protected:
WindowButtonOrderProvider();
virtual ~WindowButtonOrderProvider();
private:
static WindowButtonOrderProvider* instance_;
// Layout arrangement of the window caption buttons. On linux these will be
// set via a WindowButtonOrderObserver. On other platforms a default
// arrangement of a trailing minimize, maximize, close, will be set.
std::vector<views::FrameButton> leading_buttons_;
std::vector<views::FrameButton> trailing_buttons_;
};
} // namespace views
#endif // UI_VIEWS_WINDOW_WINDOW_BUTTON_ORDER_PROVIDER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/window/window_button_order_provider.h | C++ | unknown | 1,901 |
// 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_WINDOW_WINDOW_RESOURCES_H_
#define UI_VIEWS_WINDOW_WINDOW_RESOURCES_H_
namespace gfx {
class ImageSkia;
}
namespace views {
using FramePartImage = int;
///////////////////////////////////////////////////////////////////////////////
// WindowResources
//
// An interface implemented by an object providing images to render the
// contents of a window frame. The Window may swap in different
// implementations of this interface to render different modes. The definition
// of FramePartImage depends on the implementation.
//
class WindowResources {
public:
virtual ~WindowResources() = default;
virtual gfx::ImageSkia* GetPartImage(FramePartImage part) const = 0;
};
} // namespace views
#endif // UI_VIEWS_WINDOW_WINDOW_RESOURCES_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/window/window_resources.h | C++ | unknown | 912 |
// 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/window/window_shape.h"
#include "third_party/skia/include/core/SkPath.h"
#include "ui/gfx/geometry/size.h"
namespace views {
void GetDefaultWindowMask(const gfx::Size& size,
SkPath* window_mask) {
const SkScalar width = SkIntToScalar(size.width());
const SkScalar height = SkIntToScalar(size.height());
window_mask->moveTo(0, 3);
window_mask->lineTo(1, 3);
window_mask->lineTo(1, 1);
window_mask->lineTo(3, 1);
window_mask->lineTo(3, 0);
window_mask->lineTo(width - 3, 0);
window_mask->lineTo(width - 3, 1);
window_mask->lineTo(width - 1, 1);
window_mask->lineTo(width - 1, 3);
window_mask->lineTo(width, 3);
window_mask->lineTo(width, height - 3);
window_mask->lineTo(width - 1, height - 3);
window_mask->lineTo(width - 1, height - 1);
window_mask->lineTo(width - 3, height - 1);
window_mask->lineTo(width - 3, height);
window_mask->lineTo(3, height);
window_mask->lineTo(3, height - 1);
window_mask->lineTo(1, height - 1);
window_mask->lineTo(1, height - 3);
window_mask->lineTo(0, height - 3);
window_mask->close();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/window/window_shape.cc | C++ | unknown | 1,287 |
// 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_WINDOW_WINDOW_SHAPE_H_
#define UI_VIEWS_WINDOW_WINDOW_SHAPE_H_
#include "ui/views/views_export.h"
class SkPath;
namespace gfx {
class Size;
}
namespace views {
// Sets the window mask to a style that most likely matches
// ui/resources/window_*
VIEWS_EXPORT void GetDefaultWindowMask(const gfx::Size& size,
SkPath* window_mask);
} // namespace views
#endif // UI_VIEWS_WINDOW_WINDOW_SHAPE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/window/window_shape.h | C++ | unknown | 601 |
// 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_WORD_LOOKUP_CLIENT_H_
#define UI_VIEWS_WORD_LOOKUP_CLIENT_H_
#include "ui/views/views_export.h"
namespace gfx {
struct DecoratedText;
class Point;
} // namespace gfx
namespace views {
// An interface implemented by a view which supports word lookups.
class VIEWS_EXPORT WordLookupClient {
public:
// Retrieves the word displayed at the given |point| along with its styling
// information. |point| is in the coordinate system of the view. If no word is
// displayed at the point, returns a nearby word. |baseline_point| should
// correspond to the baseline point of the leftmost glyph of the |word| in the
// view's coordinates. Returns false, if no word can be retrieved.
virtual bool GetWordLookupDataAtPoint(const gfx::Point& point,
gfx::DecoratedText* decorated_word,
gfx::Point* baseline_point) = 0;
virtual bool GetWordLookupDataFromSelection(
gfx::DecoratedText* decorated_text,
gfx::Point* baseline_point) = 0;
protected:
virtual ~WordLookupClient() = default;
};
} // namespace views
#endif // UI_VIEWS_WORD_LOOKUP_CLIENT_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/word_lookup_client.h | C++ | unknown | 1,315 |
include_rules = [
"+content/public",
"+content/shell",
"+storage/browser/quota",
"+ui/aura",
"+ui/base",
"+ui/display",
"+ui/gfx",
"+ui/views",
"+ui/wm",
]
| Zhao-PengFei35/chromium_src_4 | ui/views_content_client/DEPS | Python | unknown | 174 |
// 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_content_client/views_content_browser_client.h"
#include <utility>
#include "content/public/browser/browser_context.h"
#include "content/public/browser/storage_partition.h"
#include "ui/views_content_client/views_content_client_main_parts.h"
namespace ui {
ViewsContentBrowserClient::ViewsContentBrowserClient(
ViewsContentClient* views_content_client)
: views_content_client_(views_content_client) {}
ViewsContentBrowserClient::~ViewsContentBrowserClient() {
}
std::unique_ptr<content::BrowserMainParts>
ViewsContentBrowserClient::CreateBrowserMainParts(
bool /* is_integration_test */) {
return ViewsContentClientMainParts::Create(views_content_client_);
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/views_content_client/views_content_browser_client.cc | C++ | unknown | 861 |
// 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_CONTENT_CLIENT_VIEWS_CONTENT_BROWSER_CLIENT_H_
#define UI_VIEWS_CONTENT_CLIENT_VIEWS_CONTENT_BROWSER_CLIENT_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "content/public/browser/content_browser_client.h"
namespace ui {
class ViewsContentClient;
class ViewsContentBrowserClient : public content::ContentBrowserClient {
public:
explicit ViewsContentBrowserClient(
ViewsContentClient* views_content_client);
ViewsContentBrowserClient(const ViewsContentBrowserClient&) = delete;
ViewsContentBrowserClient& operator=(const ViewsContentBrowserClient&) =
delete;
~ViewsContentBrowserClient() override;
// content::ContentBrowserClient:
std::unique_ptr<content::BrowserMainParts> CreateBrowserMainParts(
bool is_integration_test) override;
private:
raw_ptr<ViewsContentClient> views_content_client_;
};
} // namespace ui
#endif // UI_VIEWS_CONTENT_CLIENT_VIEWS_CONTENT_BROWSER_CLIENT_H_
| Zhao-PengFei35/chromium_src_4 | ui/views_content_client/views_content_browser_client.h | C++ | unknown | 1,104 |
// 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_content_client/views_content_client.h"
#include <utility>
#include "build/build_config.h"
#include "content/public/app/content_main.h"
#include "ui/views_content_client/views_content_main_delegate.h"
namespace ui {
#if BUILDFLAG(IS_WIN)
ViewsContentClient::ViewsContentClient(
HINSTANCE instance, sandbox::SandboxInterfaceInfo* sandbox_info)
: instance_(instance), sandbox_info_(sandbox_info) {
}
#else
ViewsContentClient::ViewsContentClient(int argc, const char** argv)
: argc_(argc), argv_(argv) {
}
#endif
ViewsContentClient::~ViewsContentClient() {
}
int ViewsContentClient::RunMain() {
ViewsContentMainDelegate delegate(this);
content::ContentMainParams params(&delegate);
#if BUILDFLAG(IS_WIN)
params.instance = instance_;
params.sandbox_info = sandbox_info_;
#else
params.argc = argc_;
params.argv = argv_;
#endif
return content::ContentMain(std::move(params));
}
void ViewsContentClient::OnPreMainMessageLoopRun(
content::BrowserContext* browser_context,
gfx::NativeWindow window_context) {
std::move(on_pre_main_message_loop_run_callback_)
.Run(browser_context, window_context);
}
void ViewsContentClient::OnResourcesLoaded() {
if (on_resources_loaded_callback_)
std::move(on_resources_loaded_callback_).Run();
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/views_content_client/views_content_client.cc | C++ | unknown | 1,463 |
// 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_CONTENT_CLIENT_VIEWS_CONTENT_CLIENT_H_
#define UI_VIEWS_CONTENT_CLIENT_VIEWS_CONTENT_CLIENT_H_
#include <utility>
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views_content_client/views_content_client_export.h"
namespace content {
class BrowserContext;
}
namespace sandbox {
struct SandboxInterfaceInfo;
}
namespace ui {
// Creates a multiprocess views runtime for running an example application.
//
// Sample usage:
//
// void InitMyApp(content::BrowserContext* browser_context,
// gfx::NativeWindow window_context) {
// // Create desired windows and views here. Runs on the UI thread.
// }
//
// #if BUILDFLAG(IS_WIN)
// int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t*, int) {
// sandbox::SandboxInterfaceInfo sandbox_info = {nullptr};
// content::InitializeSandboxInfo(&sandbox_info);
// ui::ViewsContentClient params(instance, &sandbox_info);
// #else
// int main(int argc, const char** argv) {
// ui::ViewsContentClient params(argc, argv);
// #endif
//
// params.set_on_pre_main_message_loop_run_callback(
// base::BindOnce(&InitMyApp));
// return params.RunMain();
// }
class VIEWS_CONTENT_CLIENT_EXPORT ViewsContentClient {
public:
using OnPreMainMessageLoopRunCallback =
base::OnceCallback<void(content::BrowserContext* browser_context,
gfx::NativeWindow window_context)>;
#if BUILDFLAG(IS_WIN)
ViewsContentClient(HINSTANCE instance,
sandbox::SandboxInterfaceInfo* sandbox_info);
#else
ViewsContentClient(int argc, const char** argv);
#endif
ViewsContentClient(const ViewsContentClient&) = delete;
ViewsContentClient& operator=(const ViewsContentClient&) = delete;
~ViewsContentClient();
// Runs content::ContentMain() using the ExamplesMainDelegate.
int RunMain();
// The task to run at the end of BrowserMainParts::PreMainMessageLoopRun().
// Ignored if this is not the main process.
void set_on_pre_main_message_loop_run_callback(
OnPreMainMessageLoopRunCallback callback) {
on_pre_main_message_loop_run_callback_ = std::move(callback);
}
void set_on_resources_loaded_callback(base::OnceClosure callback) {
on_resources_loaded_callback_ = std::move(callback);
}
// Calls the OnPreMainMessageLoopRun callback. |browser_context| is the
// current browser context. |window_context| is a candidate root window that
// may be null.
void OnPreMainMessageLoopRun(content::BrowserContext* browser_context,
gfx::NativeWindow window_context);
// Calls a callback to signal resources have been loaded.
void OnResourcesLoaded();
// Called by ViewsContentClientMainParts to supply the quit-closure to use
// to exit RunMain().
void set_quit_closure(base::OnceClosure quit_closure) {
quit_closure_ = std::move(quit_closure);
}
base::OnceClosure& quit_closure() { return quit_closure_; }
private:
#if BUILDFLAG(IS_WIN)
HINSTANCE instance_;
raw_ptr<sandbox::SandboxInterfaceInfo> sandbox_info_;
#else
int argc_;
raw_ptr<const char*> argv_;
#endif
OnPreMainMessageLoopRunCallback on_pre_main_message_loop_run_callback_;
base::OnceClosure on_resources_loaded_callback_;
base::OnceClosure quit_closure_;
};
} // namespace ui
#endif // UI_VIEWS_CONTENT_CLIENT_VIEWS_CONTENT_CLIENT_H_
| Zhao-PengFei35/chromium_src_4 | ui/views_content_client/views_content_client.h | C++ | unknown | 3,588 |
// 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_CONTENT_CLIENT_VIEWS_CONTENT_CLIENT_EXPORT_H_
#define UI_VIEWS_CONTENT_CLIENT_VIEWS_CONTENT_CLIENT_EXPORT_H_
// Defines VIEWS_CONTENT_CLIENT_EXPORT so that functionality implemented by the
// views_content_client module can be exported to consumers.
#if defined(COMPONENT_BUILD)
#if defined(WIN32)
#if defined(VIEWS_CONTENT_CLIENT_IMPLEMENTATION)
#define VIEWS_CONTENT_CLIENT_EXPORT __declspec(dllexport)
#else
#define VIEWS_CONTENT_CLIENT_EXPORT __declspec(dllimport)
#endif // defined(VIEWS_CONTENT_CLIENT_IMPLEMENTATION)
#else // defined(WIN32)
#if defined(VIEWS_CONTENT_CLIENT_IMPLEMENTATION)
#define VIEWS_CONTENT_CLIENT_EXPORT __attribute__((visibility("default")))
#else
#define VIEWS_CONTENT_CLIENT_EXPORT
#endif
#endif // defined(VIEWS_CONTENT_CLIENT_IMPLEMENTATION)
#else // defined(COMPONENT_BUILD)
#define VIEWS_CONTENT_CLIENT_EXPORT
#endif
#endif // UI_VIEWS_CONTENT_CLIENT_VIEWS_CONTENT_CLIENT_EXPORT_H_
| Zhao-PengFei35/chromium_src_4 | ui/views_content_client/views_content_client_export.h | C | unknown | 1,090 |
// 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_content_client/views_content_client_main_parts.h"
#include <utility>
#include "base/run_loop.h"
#include "build/build_config.h"
#include "content/public/common/result_codes.h"
#include "content/shell/browser/shell_browser_context.h"
#include "ui/base/ime/init/input_method_initializer.h"
#include "ui/views/test/desktop_test_views_delegate.h"
#include "ui/views_content_client/views_content_client.h"
namespace ui {
ViewsContentClientMainParts::ViewsContentClientMainParts(
ViewsContentClient* views_content_client)
: views_content_client_(views_content_client) {}
ViewsContentClientMainParts::~ViewsContentClientMainParts() {
}
#if !BUILDFLAG(IS_APPLE)
void ViewsContentClientMainParts::PreBrowserMain() {}
#endif
int ViewsContentClientMainParts::PreMainMessageLoopRun() {
ui::InitializeInputMethodForTesting();
browser_context_ = std::make_unique<content::ShellBrowserContext>(false);
views_delegate_ = std::make_unique<views::DesktopTestViewsDelegate>();
run_loop_ = std::make_unique<base::RunLoop>();
views_content_client()->set_quit_closure(run_loop_->QuitClosure());
return content::RESULT_CODE_NORMAL_EXIT;
}
void ViewsContentClientMainParts::PostMainMessageLoopRun() {
browser_context_.reset();
views_delegate_.reset();
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/views_content_client/views_content_client_main_parts.cc | C++ | unknown | 1,446 |
// 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_CONTENT_CLIENT_VIEWS_CONTENT_CLIENT_MAIN_PARTS_H_
#define UI_VIEWS_CONTENT_CLIENT_VIEWS_CONTENT_CLIENT_MAIN_PARTS_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "content/public/browser/browser_main_parts.h"
namespace base {
class RunLoop;
}
namespace content {
class ShellBrowserContext;
}
namespace views {
class TestViewsDelegate;
}
namespace ui {
class ViewsContentClient;
class ViewsContentClientMainParts : public content::BrowserMainParts {
public:
// Platform-specific create function.
static std::unique_ptr<ViewsContentClientMainParts> Create(
ViewsContentClient* views_content_client);
static void PreBrowserMain();
ViewsContentClientMainParts(const ViewsContentClientMainParts&) = delete;
ViewsContentClientMainParts& operator=(const ViewsContentClientMainParts&) =
delete;
~ViewsContentClientMainParts() override;
// content::BrowserMainParts:
int PreMainMessageLoopRun() override;
void PostMainMessageLoopRun() override;
content::ShellBrowserContext* browser_context() {
return browser_context_.get();
}
ViewsContentClient* views_content_client() {
return views_content_client_;
}
protected:
explicit ViewsContentClientMainParts(
ViewsContentClient* views_content_client);
#if BUILDFLAG(IS_APPLE)
views::TestViewsDelegate* views_delegate() { return views_delegate_.get(); }
#endif
private:
std::unique_ptr<content::ShellBrowserContext> browser_context_;
std::unique_ptr<views::TestViewsDelegate> views_delegate_;
raw_ptr<ViewsContentClient> views_content_client_;
std::unique_ptr<base::RunLoop> run_loop_;
};
} // namespace ui
#endif // UI_VIEWS_CONTENT_CLIENT_VIEWS_CONTENT_CLIENT_MAIN_PARTS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views_content_client/views_content_client_main_parts.h | C++ | unknown | 1,909 |
// 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_content_client/views_content_client_main_parts_aura.h"
#include <utility>
#include "build/chromeos_buildflags.h"
#if !BUILDFLAG(IS_CHROMEOS_ASH)
#include "ui/wm/core/wm_state.h"
#endif
namespace ui {
ViewsContentClientMainPartsAura::ViewsContentClientMainPartsAura(
ViewsContentClient* views_content_client)
: ViewsContentClientMainParts(views_content_client) {}
ViewsContentClientMainPartsAura::~ViewsContentClientMainPartsAura() {
}
void ViewsContentClientMainPartsAura::ToolkitInitialized() {
ViewsContentClientMainParts::ToolkitInitialized();
#if !BUILDFLAG(IS_CHROMEOS_ASH)
wm_state_ = std::make_unique<::wm::WMState>();
#endif
}
void ViewsContentClientMainPartsAura::PostMainMessageLoopRun() {
ViewsContentClientMainParts::PostMainMessageLoopRun();
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/views_content_client/views_content_client_main_parts_aura.cc | C++ | unknown | 963 |
// 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_CONTENT_CLIENT_VIEWS_CONTENT_CLIENT_MAIN_PARTS_AURA_H_
#define UI_VIEWS_CONTENT_CLIENT_VIEWS_CONTENT_CLIENT_MAIN_PARTS_AURA_H_
#include <memory>
#include "build/chromeos_buildflags.h"
#include "ui/views_content_client/views_content_client_main_parts.h"
#if !BUILDFLAG(IS_CHROMEOS_ASH)
namespace wm {
class WMState;
}
#endif
namespace ui {
class ViewsContentClientMainPartsAura : public ViewsContentClientMainParts {
public:
ViewsContentClientMainPartsAura(const ViewsContentClientMainPartsAura&) =
delete;
ViewsContentClientMainPartsAura& operator=(
const ViewsContentClientMainPartsAura&) = delete;
protected:
explicit ViewsContentClientMainPartsAura(
ViewsContentClient* views_content_client);
~ViewsContentClientMainPartsAura() override;
// content::BrowserMainParts:
void ToolkitInitialized() override;
void PostMainMessageLoopRun() override;
private:
#if !BUILDFLAG(IS_CHROMEOS_ASH)
std::unique_ptr<::wm::WMState> wm_state_;
#endif
};
} // namespace ui
#endif // UI_VIEWS_CONTENT_CLIENT_VIEWS_CONTENT_CLIENT_MAIN_PARTS_AURA_H_
| Zhao-PengFei35/chromium_src_4 | ui/views_content_client/views_content_client_main_parts_aura.h | C++ | unknown | 1,242 |
// 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 "content/public/browser/context_factory.h"
#include "content/public/common/result_codes.h"
#include "content/shell/browser/shell_browser_context.h"
#include "ui/aura/window.h"
#include "ui/views_content_client/views_content_client.h"
#include "ui/views_content_client/views_content_client_main_parts_aura.h"
#include "ui/wm/test/wm_test_helper.h"
namespace ui {
namespace {
class ViewsContentClientMainPartsChromeOS
: public ViewsContentClientMainPartsAura {
public:
explicit ViewsContentClientMainPartsChromeOS(
ViewsContentClient* views_content_client);
ViewsContentClientMainPartsChromeOS(
const ViewsContentClientMainPartsChromeOS&) = delete;
ViewsContentClientMainPartsChromeOS& operator=(
const ViewsContentClientMainPartsChromeOS&) = delete;
~ViewsContentClientMainPartsChromeOS() override {}
// content::BrowserMainParts:
int PreMainMessageLoopRun() override;
void PostMainMessageLoopRun() override;
private:
// Enable a minimal set of views::corewm to be initialized.
std::unique_ptr<::wm::WMTestHelper> wm_test_helper_;
};
ViewsContentClientMainPartsChromeOS::ViewsContentClientMainPartsChromeOS(
ViewsContentClient* views_content_client)
: ViewsContentClientMainPartsAura(views_content_client) {}
int ViewsContentClientMainPartsChromeOS::PreMainMessageLoopRun() {
ViewsContentClientMainPartsAura::PreMainMessageLoopRun();
// Set up basic pieces of views::corewm.
wm_test_helper_ = std::make_unique<wm::WMTestHelper>(gfx::Size(1024, 768));
// Ensure the X window gets mapped.
wm_test_helper_->host()->Show();
// Ensure Aura knows where to open new windows.
aura::Window* root_window = wm_test_helper_->host()->window();
views_content_client()->OnPreMainMessageLoopRun(browser_context(),
root_window);
return content::RESULT_CODE_NORMAL_EXIT;
}
void ViewsContentClientMainPartsChromeOS::PostMainMessageLoopRun() {
wm_test_helper_.reset();
ViewsContentClientMainPartsAura::PostMainMessageLoopRun();
}
} // namespace
// static
std::unique_ptr<ViewsContentClientMainParts>
ViewsContentClientMainParts::Create(ViewsContentClient* views_content_client) {
return std::make_unique<ViewsContentClientMainPartsChromeOS>(
views_content_client);
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/views_content_client/views_content_client_main_parts_chromeos.cc | C++ | unknown | 2,466 |
// 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 "content/public/common/result_codes.h"
#include "content/shell/browser/shell_browser_context.h"
#include "ui/display/screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#include "ui/views_content_client/views_content_client.h"
#include "ui/views_content_client/views_content_client_main_parts_aura.h"
namespace ui {
namespace {
class ViewsContentClientMainPartsDesktopAura
: public ViewsContentClientMainPartsAura {
public:
explicit ViewsContentClientMainPartsDesktopAura(
ViewsContentClient* views_content_client);
ViewsContentClientMainPartsDesktopAura(
const ViewsContentClientMainPartsDesktopAura&) = delete;
ViewsContentClientMainPartsDesktopAura& operator=(
const ViewsContentClientMainPartsDesktopAura&) = delete;
~ViewsContentClientMainPartsDesktopAura() override = default;
// ViewsContentClientMainPartsAura:
int PreMainMessageLoopRun() override;
void PostMainMessageLoopRun() override;
private:
std::unique_ptr<display::Screen> screen_;
};
ViewsContentClientMainPartsDesktopAura::ViewsContentClientMainPartsDesktopAura(
ViewsContentClient* views_content_client)
: ViewsContentClientMainPartsAura(views_content_client) {}
int ViewsContentClientMainPartsDesktopAura::PreMainMessageLoopRun() {
ViewsContentClientMainPartsAura::PreMainMessageLoopRun();
screen_ = views::CreateDesktopScreen();
views_content_client()->OnPreMainMessageLoopRun(browser_context(), nullptr);
return content::RESULT_CODE_NORMAL_EXIT;
}
void ViewsContentClientMainPartsDesktopAura::PostMainMessageLoopRun() {
screen_.reset();
ViewsContentClientMainPartsAura::PostMainMessageLoopRun();
}
} // namespace
// static
std::unique_ptr<ViewsContentClientMainParts>
ViewsContentClientMainParts::Create(ViewsContentClient* views_content_client) {
return std::make_unique<ViewsContentClientMainPartsDesktopAura>(
views_content_client);
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/views_content_client/views_content_client_main_parts_desktop_aura.cc | C++ | unknown | 2,081 |
// 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.
#import <Cocoa/Cocoa.h>
#include <utility>
#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/mac/scoped_nsobject.h"
#include "base/path_service.h"
#include "content/public/browser/context_factory.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/result_codes.h"
#include "content/shell/browser/shell_application_mac.h"
#include "content/shell/browser/shell_browser_context.h"
#include "ui/views/test/test_views_delegate.h"
#include "ui/views_content_client/views_content_client.h"
#include "ui/views_content_client/views_content_client_main_parts.h"
// A simple NSApplicationDelegate that provides a basic mainMenu and can
// activate a task when the application has finished loading.
@interface ViewsContentClientAppController : NSObject<NSApplicationDelegate> {
@private
base::OnceClosure _onApplicationDidFinishLaunching;
}
// Set the task to run after receiving -applicationDidFinishLaunching:.
- (void)setOnApplicationDidFinishLaunching:(base::OnceClosure)task;
@end
namespace ui {
namespace {
class ViewsContentClientMainPartsMac : public ViewsContentClientMainParts {
public:
explicit ViewsContentClientMainPartsMac(
ViewsContentClient* views_content_client);
ViewsContentClientMainPartsMac(const ViewsContentClientMainPartsMac&) =
delete;
ViewsContentClientMainPartsMac& operator=(
const ViewsContentClientMainPartsMac&) = delete;
~ViewsContentClientMainPartsMac() override;
// content::BrowserMainParts:
int PreMainMessageLoopRun() override;
private:
base::scoped_nsobject<ViewsContentClientAppController> app_controller_;
};
ViewsContentClientMainPartsMac::ViewsContentClientMainPartsMac(
ViewsContentClient* views_content_client)
: ViewsContentClientMainParts(views_content_client) {
// Cache the child process path to avoid triggering an AssertIOAllowed.
base::FilePath child_process_exe;
base::PathService::Get(content::CHILD_PROCESS_EXE, &child_process_exe);
app_controller_.reset([[ViewsContentClientAppController alloc] init]);
[[NSApplication sharedApplication] setDelegate:app_controller_];
}
int ViewsContentClientMainPartsMac::PreMainMessageLoopRun() {
ViewsContentClientMainParts::PreMainMessageLoopRun();
views_delegate()->set_context_factory(content::GetContextFactory());
// On Mac, the task must be deferred to applicationDidFinishLaunching. If not,
// the widget can activate, but (even if configured) the mainMenu won't be
// ready to switch over in the OSX UI, so it will look strange.
NSWindow* window_context = nil;
[app_controller_
setOnApplicationDidFinishLaunching:
base::BindOnce(&ViewsContentClient::OnPreMainMessageLoopRun,
base::Unretained(views_content_client()),
base::Unretained(browser_context()),
base::Unretained(window_context))];
return content::RESULT_CODE_NORMAL_EXIT;
}
ViewsContentClientMainPartsMac::~ViewsContentClientMainPartsMac() {
[[NSApplication sharedApplication] setDelegate:nil];
}
} // namespace
// static
std::unique_ptr<ViewsContentClientMainParts>
ViewsContentClientMainParts::Create(ViewsContentClient* views_content_client) {
return std::make_unique<ViewsContentClientMainPartsMac>(views_content_client);
}
// static
void ViewsContentClientMainParts::PreBrowserMain() {
// Simply instantiating an instance of ShellCrApplication serves to register
// it as the application class. Do make sure that no other code has done this
// first, though.
CHECK_EQ(NSApp, nil);
[ShellCrApplication sharedApplication];
}
} // namespace ui
@implementation ViewsContentClientAppController
- (void)setOnApplicationDidFinishLaunching:(base::OnceClosure)task {
_onApplicationDidFinishLaunching = std::move(task);
}
- (void)applicationDidFinishLaunching:(NSNotification*)aNotification {
// To get key events, the application needs to have an activation policy.
// Unbundled apps (i.e. those without an Info.plist) default to
// NSApplicationActivationPolicyProhibited.
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
// Create a basic mainMenu object using the executable filename.
base::scoped_nsobject<NSMenu> mainMenu([[NSMenu alloc] initWithTitle:@""]);
NSMenuItem* appMenuItem =
[mainMenu addItemWithTitle:@"" action:NULL keyEquivalent:@""];
[NSApp setMainMenu:mainMenu];
base::scoped_nsobject<NSMenu> appMenu([[NSMenu alloc] initWithTitle:@""]);
NSString* appName = [[NSProcessInfo processInfo] processName];
// TODO(tapted): Localize "Quit" if this is ever used for a released binary.
// At the time of writing, ui_strings.grd has "Close" but not "Quit".
NSString* quitTitle = [@"Quit " stringByAppendingString:appName];
[appMenu addItemWithTitle:quitTitle
action:@selector(terminate:)
keyEquivalent:@"q"];
[appMenuItem setSubmenu:appMenu];
CHECK([NSApp isKindOfClass:[ShellCrApplication class]]);
std::move(_onApplicationDidFinishLaunching).Run();
}
@end
| Zhao-PengFei35/chromium_src_4 | ui/views_content_client/views_content_client_main_parts_mac.mm | Objective-C++ | unknown | 5,261 |
// 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_content_client/views_content_main_delegate.h"
#include <string>
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "build/build_config.h"
#include "content/public/common/content_switches.h"
#include "content/shell/browser/shell_paths.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"
#include "ui/views_content_client/views_content_browser_client.h"
#include "ui/views_content_client/views_content_client.h"
#include "ui/views_content_client/views_content_client_main_parts.h"
#if BUILDFLAG(IS_WIN)
#include "base/logging_win.h"
#endif
namespace ui {
namespace {
#if BUILDFLAG(IS_WIN)
// {83FAC8EE-7A0E-4dbb-A3F6-6F500D7CAB1A}
const GUID kViewsContentClientProviderName =
{ 0x83fac8ee, 0x7a0e, 0x4dbb,
{ 0xa3, 0xf6, 0x6f, 0x50, 0xd, 0x7c, 0xab, 0x1a } };
#endif
} // namespace
ViewsContentMainDelegate::ViewsContentMainDelegate(
ViewsContentClient* views_content_client)
: views_content_client_(views_content_client) {
}
ViewsContentMainDelegate::~ViewsContentMainDelegate() {
}
absl::optional<int> ViewsContentMainDelegate::BasicStartupComplete() {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
std::string process_type =
command_line.GetSwitchValueASCII(switches::kProcessType);
logging::LoggingSettings settings;
settings.logging_dest =
logging::LOG_TO_SYSTEM_DEBUG_LOG | logging::LOG_TO_STDERR;
bool success = logging::InitLogging(settings);
CHECK(success);
#if BUILDFLAG(IS_WIN)
logging::LogEventProvider::Initialize(kViewsContentClientProviderName);
#endif
content::RegisterShellPathProvider();
return absl::nullopt;
}
void ViewsContentMainDelegate::PreSandboxStartup() {
base::FilePath ui_test_pak_path;
CHECK(base::PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path));
ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path);
// Load content resources to provide, e.g., sandbox configuration data on Mac.
base::FilePath content_resources_pak_path;
base::PathService::Get(base::DIR_ASSETS, &content_resources_pak_path);
ui::ResourceBundle::GetSharedInstance().AddDataPackFromPath(
content_resources_pak_path.AppendASCII("content_resources.pak"),
ui::k100Percent);
if (ui::ResourceBundle::IsScaleFactorSupported(ui::k200Percent)) {
base::FilePath ui_test_resources_200 = ui_test_pak_path.DirName().Append(
FILE_PATH_LITERAL("ui_test_200_percent.pak"));
ui::ResourceBundle::GetSharedInstance().AddDataPackFromPath(
ui_test_resources_200, ui::k200Percent);
}
views_content_client_->OnResourcesLoaded();
}
absl::optional<int> ViewsContentMainDelegate::PreBrowserMain() {
absl::optional<int> exit_code =
content::ContentMainDelegate::PreBrowserMain();
if (exit_code.has_value())
return exit_code;
ViewsContentClientMainParts::PreBrowserMain();
return absl::nullopt;
}
content::ContentClient* ViewsContentMainDelegate::CreateContentClient() {
return &content_client_;
}
content::ContentBrowserClient*
ViewsContentMainDelegate::CreateContentBrowserClient() {
browser_client_ =
std::make_unique<ViewsContentBrowserClient>(views_content_client_);
return browser_client_.get();
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/views_content_client/views_content_main_delegate.cc | C++ | unknown | 3,489 |
// 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_CONTENT_CLIENT_VIEWS_CONTENT_MAIN_DELEGATE_H_
#define UI_VIEWS_CONTENT_CLIENT_VIEWS_CONTENT_MAIN_DELEGATE_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "content/public/app/content_main_delegate.h"
#include "content/shell/common/shell_content_client.h"
namespace ui {
class ViewsContentBrowserClient;
class ViewsContentClient;
class ViewsContentMainDelegate : public content::ContentMainDelegate {
public:
explicit ViewsContentMainDelegate(ViewsContentClient* views_content_client);
ViewsContentMainDelegate(const ViewsContentMainDelegate&) = delete;
ViewsContentMainDelegate& operator=(const ViewsContentMainDelegate&) = delete;
~ViewsContentMainDelegate() override;
// content::ContentMainDelegate implementation
absl::optional<int> BasicStartupComplete() override;
void PreSandboxStartup() override;
absl::optional<int> PreBrowserMain() override;
content::ContentClient* CreateContentClient() override;
content::ContentBrowserClient* CreateContentBrowserClient() override;
private:
std::unique_ptr<ViewsContentBrowserClient> browser_client_;
content::ShellContentClient content_client_;
raw_ptr<ViewsContentClient> views_content_client_;
};
} // namespace ui
#endif // UI_VIEWS_CONTENT_CLIENT_VIEWS_CONTENT_MAIN_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views_content_client/views_content_main_delegate.h | C++ | unknown | 1,445 |
include_rules = [
"+content/public",
"+third_party/blink/public/common/input/web_gesture_event.h",
"+third_party/blink/public/mojom/loader/resource_load_info.mojom.h",
"+ui/base",
"+ui/gfx",
"+ui/webui",
]
| Zhao-PengFei35/chromium_src_4 | ui/web_dialogs/DEPS | Python | unknown | 218 |
// 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/web_dialogs/test/test_web_contents_handler.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
namespace ui {
namespace test {
TestWebContentsHandler::TestWebContentsHandler() {
}
TestWebContentsHandler::~TestWebContentsHandler() {
}
content::WebContents* TestWebContentsHandler::OpenURLFromTab(
content::BrowserContext* context,
content::WebContents* source,
const content::OpenURLParams& params) {
return NULL;
}
void TestWebContentsHandler::AddNewContents(
content::BrowserContext* context,
content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture) {}
void TestWebContentsHandler::RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) {}
} // namespace test
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/web_dialogs/test/test_web_contents_handler.cc | C++ | unknown | 1,278 |
// 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_WEB_DIALOGS_TEST_TEST_WEB_CONTENTS_HANDLER_H_
#define UI_WEB_DIALOGS_TEST_TEST_WEB_CONTENTS_HANDLER_H_
#include "ui/web_dialogs/web_dialog_web_contents_delegate.h"
namespace ui {
namespace test {
class TestWebContentsHandler
: public WebDialogWebContentsDelegate::WebContentsHandler {
public:
TestWebContentsHandler();
TestWebContentsHandler(const TestWebContentsHandler&) = delete;
TestWebContentsHandler& operator=(const TestWebContentsHandler&) = delete;
~TestWebContentsHandler() override;
private:
// Overridden from WebDialogWebContentsDelegate::WebContentsHandler:
content::WebContents* OpenURLFromTab(
content::BrowserContext* context,
content::WebContents* source,
const content::OpenURLParams& params) override;
void AddNewContents(content::BrowserContext* context,
content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture) override;
void RunFileChooser(content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) override;
};
} // namespace test
} // namespace ui
#endif // UI_WEB_DIALOGS_TEST_TEST_WEB_CONTENTS_HANDLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/web_dialogs/test/test_web_contents_handler.h | C++ | unknown | 1,656 |
// 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/web_dialogs/test/test_web_dialog_delegate.h"
#include "base/check.h"
#include "base/strings/utf_string_conversions.h"
using content::WebContents;
using content::WebUIMessageHandler;
namespace ui {
namespace test {
TestWebDialogDelegate::TestWebDialogDelegate(const GURL& url)
: url_(url),
size_(400, 400),
did_delete_(nullptr),
close_on_escape_(true) {}
TestWebDialogDelegate::~TestWebDialogDelegate() {
if (did_delete_) {
CHECK(!*did_delete_);
*did_delete_ = true;
}
}
void TestWebDialogDelegate::SetDeleteOnClosedAndObserve(
bool* destroy_observer) {
CHECK(destroy_observer);
did_delete_ = destroy_observer;
}
void TestWebDialogDelegate::SetCloseOnEscape(bool enabled) {
close_on_escape_ = enabled;
}
ModalType TestWebDialogDelegate::GetDialogModalType() const {
return MODAL_TYPE_WINDOW;
}
std::u16string TestWebDialogDelegate::GetDialogTitle() const {
return u"Test";
}
GURL TestWebDialogDelegate::GetDialogContentURL() const {
return url_;
}
void TestWebDialogDelegate::GetWebUIMessageHandlers(
std::vector<WebUIMessageHandler*>* handlers) const {
}
void TestWebDialogDelegate::GetDialogSize(gfx::Size* size) const {
*size = size_;
}
std::string TestWebDialogDelegate::GetDialogArgs() const {
return std::string();
}
void TestWebDialogDelegate::OnDialogClosed(const std::string& json_retval) {
if (did_delete_)
delete this;
}
void TestWebDialogDelegate::OnCloseContents(WebContents* source,
bool* out_close_dialog) {
*out_close_dialog = true;
}
bool TestWebDialogDelegate::ShouldShowDialogTitle() const {
return true;
}
bool TestWebDialogDelegate::ShouldCloseDialogOnEscape() const {
return close_on_escape_;
}
} // namespace test
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/web_dialogs/test/test_web_dialog_delegate.cc | C++ | unknown | 1,945 |
// 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_WEB_DIALOGS_TEST_TEST_WEB_DIALOG_DELEGATE_H_
#define UI_WEB_DIALOGS_TEST_TEST_WEB_DIALOG_DELEGATE_H_
#include <string>
#include "base/memory/raw_ptr.h"
#include "ui/gfx/geometry/size.h"
#include "ui/web_dialogs/web_dialog_delegate.h"
#include "url/gurl.h"
namespace ui {
namespace test {
class TestWebDialogDelegate : public WebDialogDelegate {
public:
explicit TestWebDialogDelegate(const GURL& url);
TestWebDialogDelegate(const TestWebDialogDelegate&) = delete;
TestWebDialogDelegate& operator=(const TestWebDialogDelegate&) = delete;
~TestWebDialogDelegate() override;
void set_size(int width, int height) {
size_.SetSize(width, height);
}
// Sets the test delegate to delete when closed, as recommended by
// WebDialogDelegate::OnDialogClosed(). |observed_destroy| must be a pointer
// to a bool, which will be set to true when the destructor is called.
void SetDeleteOnClosedAndObserve(bool* destroy_observer);
// Sets whether the dialog should close when we press Escape.
void SetCloseOnEscape(bool enabled);
// WebDialogDelegate implementation:
ModalType GetDialogModalType() const override;
std::u16string GetDialogTitle() const override;
GURL GetDialogContentURL() const override;
void GetWebUIMessageHandlers(
std::vector<content::WebUIMessageHandler*>* handlers) const override;
void GetDialogSize(gfx::Size* size) const override;
std::string GetDialogArgs() const override;
void OnDialogClosed(const std::string& json_retval) override;
void OnCloseContents(content::WebContents* source,
bool* out_close_dialog) override;
bool ShouldShowDialogTitle() const override;
bool ShouldCloseDialogOnEscape() const override;
protected:
const GURL url_;
gfx::Size size_;
raw_ptr<bool> did_delete_;
bool close_on_escape_;
};
} // namespace test
} // namespace ui
#endif // UI_WEB_DIALOGS_TEST_TEST_WEB_DIALOG_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/web_dialogs/test/test_web_dialog_delegate.h | C++ | unknown | 2,081 |
// 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/web_dialogs/web_dialog_delegate.h"
#include "ui/base/accelerators/accelerator.h"
namespace ui {
std::u16string WebDialogDelegate::GetAccessibleDialogTitle() const {
return GetDialogTitle();
}
std::string WebDialogDelegate::GetDialogName() const {
return std::string();
}
void WebDialogDelegate::GetMinimumDialogSize(gfx::Size* size) const {
GetDialogSize(size);
}
bool WebDialogDelegate::CanMaximizeDialog() const {
return false;
}
bool WebDialogDelegate::OnDialogCloseRequested() {
return true;
}
bool WebDialogDelegate::ShouldCenterDialogTitleText() const {
return false;
}
bool WebDialogDelegate::ShouldCloseDialogOnEscape() const {
return true;
}
bool WebDialogDelegate::ShouldShowCloseButton() const {
return true;
}
void WebDialogDelegate::OnDialogCloseFromWebUI(
const std::string& json_retval) {
OnDialogClosed(json_retval);
}
bool WebDialogDelegate::HandleContextMenu(
content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) {
return false;
}
bool WebDialogDelegate::HandleOpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params,
content::WebContents** out_new_contents) {
return false;
}
bool WebDialogDelegate::HandleShouldOverrideWebContentsCreation() {
return false;
}
std::vector<Accelerator> WebDialogDelegate::GetAccelerators() {
return std::vector<Accelerator>();
}
bool WebDialogDelegate::AcceleratorPressed(const Accelerator& accelerator) {
return false;
}
bool WebDialogDelegate::CheckMediaAccessPermission(
content::RenderFrameHost* render_frame_host,
const GURL& security_origin,
blink::mojom::MediaStreamType type) {
return false;
}
WebDialogDelegate::FrameKind WebDialogDelegate::GetWebDialogFrameKind() const {
return WebDialogDelegate::FrameKind::kNonClient;
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/web_dialogs/web_dialog_delegate.cc | C++ | unknown | 2,008 |
// 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_WEB_DIALOGS_WEB_DIALOG_DELEGATE_H_
#define UI_WEB_DIALOGS_WEB_DIALOG_DELEGATE_H_
#include <string>
#include <vector>
#include "content/public/browser/web_contents_delegate.h"
#include "ui/base/ui_base_types.h"
#include "ui/base/window_open_disposition.h"
#include "ui/web_dialogs/web_dialogs_export.h"
class GURL;
namespace content {
class RenderFrameHost;
class WebContents;
class WebUI;
class WebUIMessageHandler;
struct ContextMenuParams;
struct OpenURLParams;
}
namespace gfx {
class Size;
}
namespace ui {
class Accelerator;
// Implement this class to receive notifications.
class WEB_DIALOGS_EXPORT WebDialogDelegate {
public:
enum class FrameKind {
kDialog, // Does not include a title bar or frame caption buttons.
kNonClient, // Includes a non client frame view with title & buttons.
};
// Returns the modal type for this dialog. Only called once, during
// WebDialogView creation.
virtual ModalType GetDialogModalType() const = 0;
// Returns the title of the dialog.
virtual std::u16string GetDialogTitle() const = 0;
// Returns the title to be read with screen readers.
virtual std::u16string GetAccessibleDialogTitle() const;
// Returns the dialog's name identifier. Used to identify this dialog for
// state restoration.
virtual std::string GetDialogName() const;
// Get the HTML file path for the content to load in the dialog.
virtual GURL GetDialogContentURL() const = 0;
// Get WebUIMessageHandler objects to handle messages from the HTML/JS page.
// The handlers are used to send and receive messages from the page while it
// is still open. Ownership of each handler is taken over by the WebUI
// hosting the page.
virtual void GetWebUIMessageHandlers(
std::vector<content::WebUIMessageHandler*>* handlers) const = 0;
// Get the size of the dialog. Implementations can safely assume |size| is a
// valid pointer. Callers should be able to handle the case where
// implementations do not write into |size|.
virtual void GetDialogSize(gfx::Size* size) const = 0;
// Get the minimum size of the dialog. The default implementation just calls
// GetDialogSize().
virtual void GetMinimumDialogSize(gfx::Size* size) const;
// Gets the JSON string input to use when showing the dialog.
virtual std::string GetDialogArgs() const = 0;
// Returns true if the dialog can ever be resized. Default implementation
// returns true.
bool can_resize() const { return can_resize_; }
void set_can_resize(bool can_resize) { can_resize_ = can_resize; }
// Returns true if the dialog can ever be maximized. Default implementation
// returns false.
virtual bool CanMaximizeDialog() const;
// Returns true if the dialog can ever be minimized. Default implementation
// returns false.
bool can_minimize() const { return can_minimize_; }
void set_can_minimize(bool can_minimize) { can_minimize_ = can_minimize; }
// A callback to notify the delegate that |source|'s loading state has
// changed.
virtual void OnLoadingStateChanged(content::WebContents* source) {}
// A callback to notify the delegate that a web dialog has been shown.
// |webui| is the WebUI with which the dialog is associated.
virtual void OnDialogShown(content::WebUI* webui) {}
// A callback to notify the delegate that the window is requesting to be
// closed. If this returns true, the dialog is closed, otherwise the
// dialog remains open. Default implementation returns true.
virtual bool OnDialogCloseRequested();
// Called when the dialog's window is certainly about to close, but teardown
// has not started yet. This differs from OnDialogCloseRequested in that
// OnDialogCloseRequested is part of the process of deciding whether to close
// a window, while OnDialogWillClose is called as soon as it is known for
// certain that the window is about to be closed.
virtual void OnDialogWillClose() {}
// A callback to notify the delegate that the dialog is about to close due to
// the user pressing the ESC key.
virtual void OnDialogClosingFromKeyEvent() {}
// A callback to notify the delegate that the dialog closed.
// IMPORTANT: Implementations should delete |this| here (unless they've
// arranged for the delegate to be deleted in some other way, e.g. by
// registering it as a message handler in the WebUI object).
virtual void OnDialogClosed(const std::string& json_retval) = 0;
// A callback to notify the delegate that the dialog is being closed in
// response to a "dialogClose" message from WebUI.
virtual void OnDialogCloseFromWebUI(const std::string& json_retval);
// A callback to notify the delegate that the contents are requesting
// to be closed. This could be in response to a number of events
// that are handled by the WebContents. If the output parameter
// is set to true, then the dialog is closed. The default is false.
// |out_close_dialog| is never NULL.
virtual void OnCloseContents(content::WebContents* source,
bool* out_close_dialog) = 0;
// Returns true if escape should immediately close the dialog. Default is
// true.
virtual bool ShouldCloseDialogOnEscape() const;
// A callback to allow the delegate to dictate that the window should not
// have a title bar. This is useful when presenting branded interfaces.
virtual bool ShouldShowDialogTitle() const = 0;
// A callback to allow the delegate to center title text. Default is
// false.
virtual bool ShouldCenterDialogTitleText() const;
// Returns true if the dialog should show a close button in the title bar.
// Default implementation returns true.
virtual bool ShouldShowCloseButton() const;
// A callback to allow the delegate to inhibit context menu or show
// customized menu.
//
// The `render_frame_host` represents the frame that requests the context menu
// (typically this frame is focused, but this is not necessarily the case -
// see https://crbug.com/1257907#c14).
//
// Returns true iff you do NOT want the standard context menu to be
// shown (because you want to handle it yourself).
virtual bool HandleContextMenu(content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params);
// A callback to allow the delegate to open a new URL inside |source|.
// On return |out_new_contents| should contain the WebContents the URL
// is opened in. Return false to use the default handler.
virtual bool HandleOpenURLFromTab(content::WebContents* source,
const content::OpenURLParams& params,
content::WebContents** out_new_contents);
// A callback to control whether a WebContents will be created. Returns
// true to disallow the creation. Return false to use the default handler.
virtual bool HandleShouldOverrideWebContentsCreation();
// Stores the dialog bounds.
virtual void StoreDialogSize(const gfx::Size& dialog_size) {}
// Returns the accelerators handled by the delegate.
virtual std::vector<Accelerator> GetAccelerators();
// Returns true if |accelerator| is processed, otherwise false.
virtual bool AcceleratorPressed(const Accelerator& accelerator);
virtual void OnWebContentsFinishedLoad() {}
virtual void RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) {}
virtual bool CheckMediaAccessPermission(
content::RenderFrameHost* render_frame_host,
const GURL& security_origin,
blink::mojom::MediaStreamType type);
// Whether to use dialog frame view for non client frame view.
virtual FrameKind GetWebDialogFrameKind() const;
virtual ~WebDialogDelegate() = default;
private:
bool can_minimize_ = false;
bool can_resize_ = true;
};
} // namespace ui
#endif // UI_WEB_DIALOGS_WEB_DIALOG_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/web_dialogs/web_dialog_delegate.h | C++ | unknown | 8,130 |
// 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/web_dialogs/web_dialog_ui.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/lazy_instance.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/values.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "content/public/common/bindings_policy.h"
#include "ui/web_dialogs/web_dialog_delegate.h"
using content::RenderFrameHost;
using content::WebUIMessageHandler;
namespace ui {
namespace {
const char kWebDialogDelegateUserDataKey[] = "WebDialogDelegateUserData";
class WebDialogDelegateUserData : public base::SupportsUserData::Data {
public:
explicit WebDialogDelegateUserData(WebDialogDelegate* delegate)
: delegate_(delegate) {}
~WebDialogDelegateUserData() override {}
WebDialogDelegate* delegate() { return delegate_; }
private:
raw_ptr<WebDialogDelegate> delegate_; // unowned
};
} // namespace
// static
void WebDialogUIBase::SetDelegate(content::WebContents* web_contents,
WebDialogDelegate* delegate) {
web_contents->SetUserData(
&kWebDialogDelegateUserDataKey,
std::make_unique<WebDialogDelegateUserData>(delegate));
}
WebDialogUIBase::WebDialogUIBase(content::WebUI* web_ui) : web_ui_(web_ui) {}
// Don't unregister our user data. During the teardown of the WebContents, this
// will be deleted, but the WebContents will already be destroyed.
//
// This object is owned indirectly by the WebContents. WebUIs can change, so
// it's scary if this WebUI is changed out and replaced with something else,
// since the user data will still point to the old delegate. But the delegate is
// itself the owner of the WebContents for a dialog so will be in scope, and the
// HTML dialogs won't swap WebUIs anyway since they don't navigate.
WebDialogUIBase::~WebDialogUIBase() = default;
void WebDialogUIBase::CloseDialog(const base::Value::List& args) {
OnDialogClosed(args);
}
WebDialogDelegate* WebDialogUIBase::GetDelegate(
content::WebContents* web_contents) {
WebDialogDelegateUserData* user_data =
static_cast<WebDialogDelegateUserData*>(
web_contents->GetUserData(&kWebDialogDelegateUserDataKey));
return user_data ? user_data->delegate() : NULL;
}
void WebDialogUIBase::HandleRenderFrameCreated(
RenderFrameHost* render_frame_host) {
// Hook up the javascript function calls, also known as chrome.send("foo")
// calls in the HTML, to the actual C++ functions.
web_ui_->RegisterMessageCallback(
"dialogClose", base::BindRepeating(&WebDialogUIBase::OnDialogClosed,
base::Unretained(this)));
// Pass the arguments to the renderer supplied by the delegate.
std::string dialog_args;
std::vector<WebUIMessageHandler*> handlers;
WebDialogDelegate* delegate = GetDelegate(web_ui_->GetWebContents());
if (delegate) {
dialog_args = delegate->GetDialogArgs();
delegate->GetWebUIMessageHandlers(&handlers);
}
if (content::BINDINGS_POLICY_NONE !=
(web_ui_->GetBindings() & content::BINDINGS_POLICY_WEB_UI)) {
render_frame_host->SetWebUIProperty("dialogArguments", dialog_args);
}
for (WebUIMessageHandler* handler : handlers)
web_ui_->AddMessageHandler(base::WrapUnique(handler));
if (delegate)
delegate->OnDialogShown(web_ui_);
}
void WebDialogUIBase::OnDialogClosed(const base::Value::List& args) {
WebDialogDelegate* delegate = GetDelegate(web_ui_->GetWebContents());
if (delegate) {
std::string json_retval;
if (!args.empty()) {
if (args[0].is_string())
json_retval = args[0].GetString();
else
NOTREACHED() << "Could not read JSON argument";
}
delegate->OnDialogCloseFromWebUI(json_retval);
}
}
WebDialogUI::WebDialogUI(content::WebUI* web_ui)
: WebDialogUIBase(web_ui), content::WebUIController(web_ui) {}
WebDialogUI::~WebDialogUI() = default;
void WebDialogUI::WebUIRenderFrameCreated(RenderFrameHost* render_frame_host) {
HandleRenderFrameCreated(render_frame_host);
}
// Note: chrome.send() must always be enabled for dialogs, since dialogs rely on
// chrome.send() to notify their handlers that the dialog should be closed. See
// the "dialogClose" message handler above in
// WebDialogUIBase::HandleRenderFrameCreated().
MojoWebDialogUI::MojoWebDialogUI(content::WebUI* web_ui)
: WebDialogUIBase(web_ui),
MojoWebUIController(web_ui, /*enable_chrome_send=*/true) {}
MojoWebDialogUI::~MojoWebDialogUI() = default;
void MojoWebDialogUI::WebUIRenderFrameCreated(
content::RenderFrameHost* render_frame_host) {
content::WebUIController::WebUIRenderFrameCreated(render_frame_host);
HandleRenderFrameCreated(render_frame_host);
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/web_dialogs/web_dialog_ui.cc | C++ | unknown | 5,045 |
// 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_WEB_DIALOGS_WEB_DIALOG_UI_H_
#define UI_WEB_DIALOGS_WEB_DIALOG_UI_H_
#include "base/memory/raw_ptr.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_ui_controller.h"
#include "ui/base/ui_base_types.h"
#include "ui/web_dialogs/web_dialogs_export.h"
#include "ui/webui/mojo_web_ui_controller.h"
#include "url/gurl.h"
namespace content {
class WebContents;
}
namespace ui {
class WebDialogDelegate;
class WEB_DIALOGS_EXPORT WebDialogUIBase {
public:
// Sets the delegate on the WebContents.
static void SetDelegate(content::WebContents* web_contents,
WebDialogDelegate* delegate);
WebDialogUIBase(content::WebUI* web_ui);
WebDialogUIBase(const WebDialogUIBase&) = delete;
WebDialogUIBase& operator=(const WebDialogUIBase&) = delete;
// Close the dialog, passing the specified arguments to the close handler.
void CloseDialog(const base::Value::List& args);
protected:
virtual ~WebDialogUIBase();
// Prepares |render_frame_host| to host a dialog.
void HandleRenderFrameCreated(content::RenderFrameHost* render_frame_host);
private:
// Gets the delegate for the WebContent set with SetDelegate.
static WebDialogDelegate* GetDelegate(content::WebContents* web_contents);
// JS message handler.
void OnDialogClosed(const base::Value::List& args);
raw_ptr<content::WebUI> web_ui_;
};
// Displays file URL contents inside a modal web dialog.
//
// This application really should not use WebContents + WebUI. It should instead
// just embed a RenderView in a dialog and be done with it.
//
// Before loading a URL corresponding to this WebUI, the caller should set its
// delegate as user data on the WebContents by calling SetDelegate(). This WebUI
// will pick it up from there and call it back. This is a bit of a hack to allow
// the dialog to pass its delegate to the Web UI without having nasty accessors
// on the WebContents. The correct design using RVH directly would avoid all of
// this.
class WEB_DIALOGS_EXPORT WebDialogUI : public WebDialogUIBase,
public content::WebUIController {
public:
// When created, the delegate should already be set as user data on the
// WebContents.
explicit WebDialogUI(content::WebUI* web_ui);
~WebDialogUI() override;
WebDialogUI(const WebDialogUI&) = delete;
WebDialogUI& operator=(const WebDialogUI&) = delete;
private:
// content::WebUIController:
void WebUIRenderFrameCreated(
content::RenderFrameHost* render_frame_host) override;
};
// Displays file URL contents inside a modal web dialog while also enabling
// Mojo calls to be made from within the dialog.
class WEB_DIALOGS_EXPORT MojoWebDialogUI : public WebDialogUIBase,
public MojoWebUIController {
public:
// When created, the delegate should already be set as user data on the
// WebContents.
explicit MojoWebDialogUI(content::WebUI* web_ui);
~MojoWebDialogUI() override;
MojoWebDialogUI(const MojoWebDialogUI&) = delete;
MojoWebDialogUI& operator=(const MojoWebDialogUI&) = delete;
private:
// content::WebUIController:
void WebUIRenderFrameCreated(
content::RenderFrameHost* render_frame_host) override;
};
} // namespace ui
#endif // UI_WEB_DIALOGS_WEB_DIALOG_UI_H_
| Zhao-PengFei35/chromium_src_4 | ui/web_dialogs/web_dialog_ui.h | C++ | unknown | 3,481 |
// 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/web_dialogs/web_dialog_ui.h"
#include "content/public/common/bindings_policy.h"
#include "content/public/test/test_web_ui.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace ui {
TEST(WebDialogUITest, NoBindingsSetForWebDialogUI) {
content::TestWebUI test_web_ui;
EXPECT_EQ(0, test_web_ui.GetBindings());
WebDialogUI web_dialog_ui(&test_web_ui);
EXPECT_EQ(0, test_web_ui.GetBindings());
}
TEST(MojoWebDialogUITest, ChromeSendAndMojoBindingsForMojoWebDialogUI) {
content::TestWebUI test_web_ui;
EXPECT_EQ(0, test_web_ui.GetBindings());
MojoWebDialogUI web_dialog_ui(&test_web_ui);
// MojoWebDialogUIs rely on both Mojo and chrome.send().
EXPECT_EQ(
content::BINDINGS_POLICY_MOJO_WEB_UI | content::BINDINGS_POLICY_WEB_UI,
test_web_ui.GetBindings());
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/web_dialogs/web_dialog_ui_unittest.cc | C++ | unknown | 972 |
// 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/web_dialogs/web_dialog_web_contents_delegate.h"
#include <utility>
#include "base/check.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/web_contents.h"
#include "third_party/blink/public/common/input/web_gesture_event.h"
using content::BrowserContext;
using content::OpenURLParams;
using content::WebContents;
namespace ui {
// Incognito profiles are not long-lived, so we always want to store a
// non-incognito profile.
//
// TODO(akalin): Should we make it so that we have a default incognito
// profile that's long-lived? Of course, we'd still have to clear it out
// when all incognito browsers close.
WebDialogWebContentsDelegate::WebDialogWebContentsDelegate(
content::BrowserContext* browser_context,
std::unique_ptr<WebContentsHandler> handler)
: browser_context_(browser_context), handler_(std::move(handler)) {
DCHECK(handler_);
}
WebDialogWebContentsDelegate::~WebDialogWebContentsDelegate() {
}
void WebDialogWebContentsDelegate::Detach() {
browser_context_ = nullptr;
}
WebContents* WebDialogWebContentsDelegate::OpenURLFromTab(
WebContents* source, const OpenURLParams& params) {
return handler_->OpenURLFromTab(browser_context_, source, params);
}
void WebDialogWebContentsDelegate::AddNewContents(
WebContents* source,
std::unique_ptr<WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) {
// TODO(erikchen): Refactor AddNewContents to take strong ownership semantics.
// https://crbug.com/832879.
handler_->AddNewContents(browser_context_, source, std::move(new_contents),
target_url, disposition, window_features,
user_gesture);
}
bool WebDialogWebContentsDelegate::PreHandleGestureEvent(
WebContents* source,
const blink::WebGestureEvent& event) {
// Disable pinch zooming.
return blink::WebInputEvent::IsPinchGestureEventType(event.GetType());
}
void WebDialogWebContentsDelegate::RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) {
handler_->RunFileChooser(render_frame_host, listener, params);
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/web_dialogs/web_dialog_web_contents_delegate.cc | C++ | unknown | 2,523 |
// 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_WEB_DIALOGS_WEB_DIALOG_WEB_CONTENTS_DELEGATE_H_
#define UI_WEB_DIALOGS_WEB_DIALOG_WEB_CONTENTS_DELEGATE_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "content/public/browser/web_contents_delegate.h"
#include "ui/web_dialogs/web_dialogs_export.h"
namespace blink {
namespace mojom {
class FileChooserParams;
}
} // namespace blink
namespace content {
class BrowserContext;
class FileSelectListener;
class RenderFrameHost;
}
namespace ui {
// This class implements (and mostly ignores) most of
// content::WebContentsDelegate for use in a Web dialog. Subclasses need only
// override a few methods instead of the everything from
// content::WebContentsDelegate; this way, implementations on all platforms
// behave consistently.
class WEB_DIALOGS_EXPORT WebDialogWebContentsDelegate
: public content::WebContentsDelegate {
public:
// Handles OpenURLFromTab and AddNewContents for WebDialogWebContentsDelegate.
class WebContentsHandler {
public:
virtual ~WebContentsHandler() {}
virtual content::WebContents* OpenURLFromTab(
content::BrowserContext* context,
content::WebContents* source,
const content::OpenURLParams& params) = 0;
virtual void AddNewContents(
content::BrowserContext* context,
content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture) = 0;
// This is added to allow the injection of a file chooser handler.
// The WebDialogWebContentsDelegate's original implementation does not
// do anything for file chooser request
virtual void RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) = 0;
};
// |context| and |handler| must be non-NULL.
WebDialogWebContentsDelegate(content::BrowserContext* context,
std::unique_ptr<WebContentsHandler> handler);
WebDialogWebContentsDelegate(const WebDialogWebContentsDelegate&) = delete;
WebDialogWebContentsDelegate& operator=(const WebDialogWebContentsDelegate&) =
delete;
~WebDialogWebContentsDelegate() override;
// The returned browser context is guaranteed to be original if non-NULL.
content::BrowserContext* browser_context() const {
return browser_context_;
}
// Calling this causes all following events sent from the
// WebContents object to be ignored. It also makes all following
// calls to browser_context() return NULL.
void Detach();
// content::WebContentsDelegate declarations.
content::WebContents* OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) override;
void AddNewContents(content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) override;
bool PreHandleGestureEvent(content::WebContents* source,
const blink::WebGestureEvent& event) override;
void RunFileChooser(content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) override;
private:
// Weak pointer. Always an original profile.
raw_ptr<content::BrowserContext> browser_context_;
std::unique_ptr<WebContentsHandler> const handler_;
};
} // namespace ui
#endif // UI_WEB_DIALOGS_WEB_DIALOG_WEB_CONTENTS_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/web_dialogs/web_dialog_web_contents_delegate.h | C++ | unknown | 4,042 |
// 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_WEB_DIALOGS_WEB_DIALOGS_EXPORT_H_
#define UI_WEB_DIALOGS_WEB_DIALOGS_EXPORT_H_
// Defines WEB_DIALOGS_EXPORT so that functionality implemented by the
// web_dialogs module can be exported to consumers.
#if defined(COMPONENT_BUILD)
#if defined(WIN32)
#if defined(WEB_DIALOGS_IMPLEMENTATION)
#define WEB_DIALOGS_EXPORT __declspec(dllexport)
#else
#define WEB_DIALOGS_EXPORT __declspec(dllimport)
#endif // defined(WEB_DIALOGS_IMPLEMENTATION)
#else // defined(WIN32)
#if defined(WEB_DIALOGS_IMPLEMENTATION)
#define WEB_DIALOGS_EXPORT __attribute__((visibility("default")))
#else
#define WEB_DIALOGS_EXPORT
#endif
#endif
#else // defined(COMPONENT_BUILD)
#define WEB_DIALOGS_EXPORT
#endif
#endif // UI_WEB_DIALOGS_WEB_DIALOGS_EXPORT_H_
| Zhao-PengFei35/chromium_src_4 | ui/web_dialogs/web_dialogs_export.h | C | unknown | 897 |
include_rules = [
"+content/public",
"+mojo/public",
"+net",
"+services/service_manager/public/cpp/binder_registry.h",
"+ui/base",
"+ui/gfx",
"+components/content_settings/core",
"+components/page_image_service"
]
| Zhao-PengFei35/chromium_src_4 | ui/webui/DEPS | Python | unknown | 230 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/webui/color_change_listener/color_change_handler.h"
#include "content/public/browser/web_ui_data_source.h"
#include "ui/base/webui/resource_path.h"
namespace ui {
ColorChangeHandler::ColorChangeHandler(
content::WebContents* web_contents,
mojo::PendingReceiver<color_change_listener::mojom::PageHandler>
pending_page_handler)
: WebContentsObserver(web_contents),
page_handler_(this, std::move(pending_page_handler)) {}
ColorChangeHandler::~ColorChangeHandler() = default;
void ColorChangeHandler::SetPage(
mojo::PendingRemote<color_change_listener::mojom::Page> pending_page) {
page_.Bind(std::move(pending_page));
}
void ColorChangeHandler::OnColorProviderChanged() {
if (page_)
page_->OnColorProviderChanged();
}
} // namespace ui | Zhao-PengFei35/chromium_src_4 | ui/webui/color_change_listener/color_change_handler.cc | C++ | unknown | 935 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_WEBUI_COLOR_CHANGE_LISTENER_COLOR_CHANGE_HANDLER_H_
#define UI_WEBUI_COLOR_CHANGE_LISTENER_COLOR_CHANGE_HANDLER_H_
#include "content/public/browser/web_contents_observer.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "ui/webui/resources/cr_components/color_change_listener/color_change_listener.mojom.h"
namespace ui {
// Handles ColorProvider related communication between C++ and WebUI in the
// renderer.
class ColorChangeHandler : public content::WebContentsObserver,
public color_change_listener::mojom::PageHandler {
public:
ColorChangeHandler(
content::WebContents* web_contents,
mojo::PendingReceiver<color_change_listener::mojom::PageHandler>
pending_page_handler);
ColorChangeHandler(const ColorChangeHandler&) = delete;
ColorChangeHandler& operator=(const ColorChangeHandler&) = delete;
~ColorChangeHandler() override;
// content::WebContentsObserver:
void OnColorProviderChanged() override;
// color_change_listener::mojom::PageHandler:
void SetPage(mojo::PendingRemote<color_change_listener::mojom::Page>
pending_page) override;
private:
mojo::Remote<color_change_listener::mojom::Page> page_;
mojo::Receiver<color_change_listener::mojom::PageHandler> page_handler_;
};
} // namespace ui
#endif // CHROME_BROWSER_UI_WEBUI_COLOR_CHANGE_LISTENER_COLOR_CHANGE_HANDLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/webui/color_change_listener/color_change_handler.h | C++ | unknown | 1,646 |