1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
|
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
#pragma allow_unsafe_libc_calls
#endif
#include "components/eye_dropper/eye_dropper_view.h"
#include <utility>
#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "build/build_config.h"
#include "components/color/color_id.h"
#include "components/eye_dropper/features.h"
#include "content/public/browser/desktop_capture.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/web_contents.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/mojom/ui_base_types.mojom-shared.h"
#include "ui/display/screen.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/widget/widget.h"
#if BUILDFLAG(IS_WIN)
#include "base/win/windows_version.h"
#endif
#if BUILDFLAG(IS_CHROMEOS)
#include "ui/aura/window_tree_host.h"
#endif
namespace eye_dropper {
class EyeDropperView::ViewPositionHandler {
public:
explicit ViewPositionHandler(EyeDropperView* owner);
ViewPositionHandler(const ViewPositionHandler&) = delete;
ViewPositionHandler& operator=(const ViewPositionHandler&) = delete;
~ViewPositionHandler();
private:
void UpdateViewPosition();
// Timer used for updating the window location.
base::RepeatingTimer timer_;
raw_ptr<EyeDropperView> owner_;
};
EyeDropperView::ViewPositionHandler::ViewPositionHandler(EyeDropperView* owner)
: owner_(owner) {
// TODO(iopopesc): Use SetCapture instead of a timer when support for
// activating the eye dropper without closing the color popup is added.
timer_.Start(FROM_HERE, base::Hertz(60), this,
&EyeDropperView::ViewPositionHandler::UpdateViewPosition);
}
EyeDropperView::ViewPositionHandler::~ViewPositionHandler() {
timer_.Stop();
}
void EyeDropperView::ViewPositionHandler::UpdateViewPosition() {
owner_->OnCursorPositionUpdate(
display::Screen::GetScreen()->GetCursorScreenPoint());
}
class EyeDropperView::ScreenCapturer
: public webrtc::DesktopCapturer::Callback {
public:
explicit ScreenCapturer(EyeDropperView* owner);
ScreenCapturer(const ScreenCapturer&) = delete;
ScreenCapturer& operator=(const ScreenCapturer&) = delete;
~ScreenCapturer() override = default;
// webrtc::DesktopCapturer::Callback:
void OnCaptureResult(webrtc::DesktopCapturer::Result result,
std::unique_ptr<webrtc::DesktopFrame> frame) override;
void CaptureScreen(std::optional<webrtc::DesktopCapturer::SourceId> screen);
SkBitmap GetBitmap() const;
SkColor GetColor(int x, int y) const;
int original_offset_x() const;
int original_offset_y() const;
private:
raw_ptr<EyeDropperView> owner_;
std::unique_ptr<webrtc::DesktopCapturer> capturer_;
SkBitmap frame_;
int original_offset_x_;
int original_offset_y_;
};
EyeDropperView::ScreenCapturer::ScreenCapturer(EyeDropperView* owner)
: owner_(owner) {
static bool allow_wgc_screen_capturer =
#if BUILDFLAG(IS_WIN)
// Allow WGC screen capture if Windows version is greater or equal
// than 10.0.20348.0, as the following API, which controls if a border is
// to be painted around the captured content, needs to be present as the
// border should not be shown during eye dropper color selection:
// https://learn.microsoft.com/en-us/uwp/api/windows.graphics.capture.graphicscapturesession.isborderrequired
base::win::GetVersion() >= base::win::Version::SERVER_2022 &&
#endif // BUILDFLAG(IS_WIN)
base::FeatureList::IsEnabled(features::kAllowEyeDropperWGCScreenCapture);
auto options = content::desktop_capture::CreateDesktopCaptureOptions();
#if defined(RTC_ENABLE_WIN_WGC)
if (allow_wgc_screen_capturer) {
options.set_allow_wgc_screen_capturer(true);
}
#endif // defined(RTC_ENABLE_WIN_WGC)
// TODO(iopopesc): Update the captured frame after a period of time to match
// latest content on screen.
capturer_ = content::desktop_capture::CreateScreenCapturer(
options, /*for_snapshot=*/true);
if (capturer_) {
capturer_->Start(this);
if (allow_wgc_screen_capturer) {
capturer_->SelectSource(webrtc::kFullDesktopScreenId);
}
}
// On ChromeOS this will capture `Screen::GetDisplayForNewWindows()`.
CaptureScreen(std::nullopt);
}
void EyeDropperView::ScreenCapturer::CaptureScreen(
std::optional<webrtc::DesktopCapturer::SourceId> screen) {
if (capturer_) {
if (screen) {
capturer_->SelectSource(*screen);
}
capturer_->CaptureFrame();
}
}
void EyeDropperView::ScreenCapturer::OnCaptureResult(
webrtc::DesktopCapturer::Result result,
std::unique_ptr<webrtc::DesktopFrame> frame) {
if (result != webrtc::DesktopCapturer::Result::SUCCESS) {
return;
}
frame_.allocN32Pixels(frame->size().width(), frame->size().height(), true);
memcpy(frame_.getAddr32(0, 0), frame->data(),
frame->size().height() * frame->stride());
frame_.setImmutable();
// The captured frame is in full desktop coordinates. E.g. the top left
// monitor should start from (0, 0), so we need to compute the correct
// origins.
original_offset_x_ = 0;
original_offset_y_ = 0;
for (const auto& display : display::Screen::GetScreen()->GetAllDisplays()) {
#if BUILDFLAG(IS_WIN)
// The window parameter is intentionally passed as nullptr on Windows
// because a non-null window parameter causes errors when restoring windows
// to saved positions in variable-DPI situations. See
// https://crbug.com/1224715 for details.
gfx::Rect scaled_bounds =
display::Screen::GetScreen()->DIPToScreenRectInWindow(
/*window=*/nullptr, display.bounds());
#else
gfx::Rect scaled_bounds = gfx::ScaleToEnclosingRect(
display.bounds(), display.device_scale_factor());
#endif
if (scaled_bounds.origin().x() < original_offset_x_) {
original_offset_x_ = scaled_bounds.origin().x();
}
if (scaled_bounds.origin().y() < original_offset_y_) {
original_offset_y_ = scaled_bounds.origin().y();
}
}
owner_->OnScreenCaptured();
}
SkBitmap EyeDropperView::ScreenCapturer::GetBitmap() const {
return frame_;
}
SkColor EyeDropperView::ScreenCapturer::GetColor(int x, int y) const {
// It's not clear how control can reach here with out-of-bounds coordinates,
// but avoid a crash if it does.
return (x < 0 || x >= frame_.width() || y < 0 || y >= frame_.height())
? gfx::kPlaceholderColor
: frame_.getColor(x, y);
}
int EyeDropperView::ScreenCapturer::original_offset_x() const {
return original_offset_x_;
}
int EyeDropperView::ScreenCapturer::original_offset_y() const {
return original_offset_y_;
}
EyeDropperView::EyeDropperView(gfx::NativeView parent,
gfx::NativeView event_handler,
content::EyeDropperListener* listener)
: listener_(listener),
view_position_handler_(std::make_unique<ViewPositionHandler>(this)),
screen_capturer_(std::make_unique<ScreenCapturer>(this)) {
SetModalType(ui::mojom::ModalType::kWindow);
// TODO(pbos): Remove this, perhaps by separating the contents view from the
// EyeDropper/WidgetDelegate.
set_owned_by_client(OwnedByClientPassKey());
SetPreferredSize(GetSize());
#if BUILDFLAG(IS_LINUX)
// Use TYPE_MENU for Linux to ensure that the eye dropper view is displayed
// above the color picker.
views::Widget::InitParams params(
views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET,
views::Widget::InitParams::TYPE_MENU);
#else
views::Widget::InitParams params(
views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET,
views::Widget::InitParams::TYPE_POPUP);
#endif
params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent;
// Use software compositing to prevent situations when the widget is not
// translucent when moved fast.
// TODO(iopopesc): Investigate if this is a compositor bug or this is indeed
// an intentional limitation.
params.force_software_compositing = true;
params.z_order = ui::ZOrderLevel::kFloatingWindow;
params.name = "MagnifierHost";
params.parent = parent;
params.delegate = this;
views::Widget* widget = new views::Widget();
widget->Init(std::move(params));
widget->SetContentsView(this);
HideCursor();
pre_dispatch_handler_ =
std::make_unique<PreEventDispatchHandler>(this, event_handler);
widget->Show();
CaptureInput();
auto* screen = display::Screen::GetScreen();
gfx::Point initial_position = screen->GetCursorScreenPoint();
#if BUILDFLAG(IS_CHROMEOS)
if (screen->InTabletMode()) {
initial_position =
screen->GetDisplayForNewWindows().work_area().CenterPoint();
}
#endif
UpdatePosition(initial_position);
// The ignore selection time should be long enough to allow the user to see
// the UI.
ignore_selection_time_ = base::TimeTicks::Now() + base::Milliseconds(500);
#if BUILDFLAG(IS_CHROMEOS)
// Add an observation so the capture can be updated as the eye dropper window
// moves between displays.
window_observation_.Observe(GetWidget()->GetNativeWindow());
#endif
}
EyeDropperView::~EyeDropperView() {
if (GetWidget()) {
GetWidget()->CloseNow();
}
}
void EyeDropperView::OnCursorPositionUpdate(gfx::Point cursor_position) {
// The view can be moved by either mouse or touch. Only move it to the cursor
// position when cursor changes.
if (std::exchange(last_cursor_position_, cursor_position) !=
cursor_position) {
UpdatePosition(std::move(cursor_position));
}
}
void EyeDropperView::OnPaint(gfx::Canvas* view_canvas) {
if (screen_capturer_->GetBitmap().drawsNothing()) {
return;
}
const float diameter = GetDiameter();
constexpr float kPixelSize = 10;
const gfx::Size padding((size().width() - diameter) / 2,
(size().height() - diameter) / 2);
if (views::Widget::IsWindowCompositingSupported()) {
// Clip circle for magnified projection only when the widget
// supports translucency.
SkPath clip_path;
clip_path.addOval(SkRect::MakeXYWH(padding.width(), padding.height(),
diameter, diameter));
clip_path.close();
view_canvas->ClipPath(clip_path, true);
}
// Project pixels.
const int pixel_count = diameter / kPixelSize;
const SkBitmap frame = screen_capturer_->GetBitmap();
gfx::Point center_position_px;
#if BUILDFLAG(IS_CHROMEOS)
// ChromeOS only captures a single display at a time, and we need to convert
// the cursor position to display (root window) local pixel coordinates.
aura::Window* window = GetWidget()->GetNativeWindow();
const gfx::Point center_position =
window->GetBoundsInRootWindow().CenterPoint();
center_position_px =
window->GetHost()->GetRootTransform().MapPoint(center_position);
#else
// The captured frame is not scaled so we need to use widget's bounds in
// pixels to have the magnified region match cursor position.
center_position_px =
display::Screen::GetScreen()
->DIPToScreenRectInWindow(GetWidget()->GetNativeWindow(),
GetWidget()->GetWindowBoundsInScreen())
.CenterPoint();
center_position_px.Offset(-screen_capturer_->original_offset_x(),
-screen_capturer_->original_offset_y());
#endif
view_canvas->DrawImageInt(gfx::ImageSkia::CreateFrom1xBitmap(frame),
center_position_px.x() - pixel_count / 2,
center_position_px.y() - pixel_count / 2,
pixel_count, pixel_count, padding.width(),
padding.height(), diameter, diameter, false);
// Store the pixel color under the cursor as it is the last color seen
// by the user before selection.
selected_color_ = screen_capturer_->GetColor(center_position_px.x(),
center_position_px.y());
// Paint grid.
const auto* color_provider = GetColorProvider();
cc::PaintFlags flags;
flags.setStrokeWidth(1);
flags.setStyle(cc::PaintFlags::kStroke_Style);
flags.setColor(color_provider->GetColor(color::kColorEyedropperGrid));
for (int i = 0; i < pixel_count; ++i) {
view_canvas->DrawLine(
gfx::PointF(padding.width() + i * kPixelSize, padding.height()),
gfx::PointF(padding.width() + i * kPixelSize,
size().height() - padding.height()),
flags);
view_canvas->DrawLine(
gfx::PointF(padding.width(), padding.height() + i * kPixelSize),
gfx::PointF(size().width() - padding.width(),
padding.height() + i * kPixelSize),
flags);
}
// Paint central pixel.
gfx::RectF pixel((size().width() - kPixelSize) / 2,
(size().height() - kPixelSize) / 2, kPixelSize, kPixelSize);
flags.setAntiAlias(true);
flags.setColor(
color_provider->GetColor(color::kColorEyedropperCentralPixelOuterRing));
flags.setStrokeWidth(2);
pixel.Inset(-0.5f);
view_canvas->DrawRect(pixel, flags);
flags.setColor(
color_provider->GetColor(color::kColorEyedropperCentralPixelInnerRing));
flags.setStrokeWidth(1);
pixel.Inset(0.5f);
view_canvas->DrawRect(pixel, flags);
// Paint outline.
flags.setStrokeWidth(2);
flags.setColor(color_provider->GetColor(color::kColorEyedropperBoundary));
flags.setAntiAlias(true);
if (views::Widget::IsWindowCompositingSupported()) {
view_canvas->DrawCircle(
gfx::PointF(size().width() / 2, size().height() / 2), diameter / 2,
flags);
} else {
view_canvas->DrawRect(bounds(), flags);
}
OnPaintBorder(view_canvas);
}
void EyeDropperView::WindowClosing() {
ShowCursor();
pre_dispatch_handler_.reset();
}
void EyeDropperView::OnWidgetMove() {
// Trigger a repaint since because the widget was moved, the content of the
// view needs to be updated.
SchedulePaint();
}
#if BUILDFLAG(IS_CHROMEOS)
void EyeDropperView::OnWindowAddedToRootWindow(aura::Window* window) {
display::Display display =
display::Screen::GetScreen()->GetDisplayNearestWindow(window);
CaptureScreen(display.id());
}
void EyeDropperView::OnWindowDestroying(aura::Window* window) {
window_observation_.Reset();
}
#endif
void EyeDropperView::CaptureScreen(
std::optional<webrtc::DesktopCapturer::SourceId> screen) {
screen_capturer_->CaptureScreen(screen);
}
void EyeDropperView::OnScreenCaptured() {
SchedulePaint();
}
void EyeDropperView::UpdatePosition(gfx::Point position) {
GetWidget()->SetBounds(
gfx::Rect(gfx::Point(position.x() - size().width() / 2,
position.y() - size().height() / 2),
size()));
}
void EyeDropperView::OnColorSelected() {
if (!selected_color_.has_value()) {
listener_->ColorSelectionCanceled();
return;
}
// Prevent the user from selecting a color for a period of time.
if (base::TimeTicks::Now() <= ignore_selection_time_) {
return;
}
// Use the last selected color and notify listener.
listener_->ColorSelected(selected_color_.value());
}
void EyeDropperView::OnColorSelectionCanceled() {
listener_->ColorSelectionCanceled();
}
BEGIN_METADATA(EyeDropperView)
ADD_READONLY_PROPERTY_METADATA(gfx::Size, Size)
ADD_READONLY_PROPERTY_METADATA(float, Diameter)
END_METADATA
} // namespace eye_dropper
|