File: accessibility_focus_highlight_browsertest.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (301 lines) | stat: -rw-r--r-- 11,510 bytes parent folder | download | duplicates (5)
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
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/accessibility/accessibility_focus_highlight.h"

#include <math.h>

#include "base/files/file_util.h"
#include "base/path_service.h"
#include "base/test/test_future.h"
#include "build/build_config.h"
#include "cc/test/pixel_comparator.h"
#include "cc/test/pixel_test_utils.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/color/chrome_color_id.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/viz/common/frame_sinks/copy_output_request.h"
#include "components/viz/common/frame_sinks/copy_output_result.h"
#include "content/public/browser/focused_node_details.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/focus_changed_observer.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/compositor/layer.h"
#include "ui/gfx/image/image.h"
#include "ui/snapshot/snapshot.h"
#include "ui/views/widget/widget.h"

#if BUILDFLAG(IS_MAC)
#include "base/mac/mac_util.h"
#endif

// To rebaseline this test on all platforms:
// 1. Run a CQ+1 dry run.
// 2. Click the failing bots for android, windows, mac, and linux.
// 3. Find the failing browser_tests step.
// 4. Click the "Deterministic failure" link for the failing test case.
// 5. Copy the "Actual pixels" data url and paste into browser.
// 6. Save the image into your chromium checkout in
//    chrome/test/data/accessibility.

class AccessibilityFocusHighlightBrowserTest : public InProcessBrowserTest {
 public:
  AccessibilityFocusHighlightBrowserTest() = default;
  ~AccessibilityFocusHighlightBrowserTest() override = default;
  AccessibilityFocusHighlightBrowserTest(
      const AccessibilityFocusHighlightBrowserTest&) = delete;
  AccessibilityFocusHighlightBrowserTest& operator=(
      const AccessibilityFocusHighlightBrowserTest&) = delete;

  // InProcessBrowserTest overrides:
  void SetUp() override {
    EnablePixelOutput();
    InProcessBrowserTest::SetUp();
  }

  bool ColorsApproximatelyEqual(SkColor color1, SkColor color2) {
    return abs(static_cast<int>(SkColorGetR(color1)) -
               static_cast<int>(SkColorGetR(color2))) < 50 &&
           abs(static_cast<int>(SkColorGetG(color1)) -
               static_cast<int>(SkColorGetG(color2))) < 50 &&
           abs(static_cast<int>(SkColorGetB(color1)) -
               static_cast<int>(SkColorGetB(color2))) < 50;
  }

  float CountPercentPixelsWithColor(const gfx::Image& image, SkColor color) {
    SkBitmap bitmap = image.AsBitmap();
    int count = 0;
    for (int x = 0; x < bitmap.width(); ++x) {
      for (int y = 0; y < bitmap.height(); ++y) {
        if (ColorsApproximatelyEqual(color, bitmap.getColor(x, y))) {
          count++;
        }
      }
    }
    return count * 100.0f / (bitmap.width() * bitmap.height());
  }

  gfx::Image CaptureWindowContents() {
    BrowserView* browser_view =
        BrowserView::GetBrowserViewForBrowser(browser());
    views::Widget* widget = browser_view->GetWidget();
    gfx::Rect bounds = widget->GetWindowBoundsInScreen();
    bounds.Offset(-bounds.OffsetFromOrigin());
    gfx::NativeView native_view = widget->GetNativeView();

    // Keep trying until we get a successful capture.
    while (true) {
      base::test::TestFuture<gfx::Image> future;
      ui::GrabViewSnapshot(native_view, bounds, future.GetCallback());
      gfx::Image result_image = future.Take();

      if (result_image.Size().IsEmpty()) {
        LOG(INFO) << "Bitmap not correct size, trying to capture again";
        continue;
      }

      // Skip through every 16th pixel (just for speed, no need to check
      // every single one). If we find at least one opaque pixel then we
      // assume we got a valid image. If the capture fails we sometimes get
      // an all transparent image, but when it succeeds there can be a
      // transparent edge.
      bool found_opaque_pixel = false;
      for (int x = 0; x < bounds.width() && !found_opaque_pixel; x += 16) {
        for (int y = 0; y < bounds.height() && !found_opaque_pixel; y += 16) {
          if (SkColorGetA(result_image.AsBitmap().getColor(x, y)) ==
              SK_AlphaOPAQUE) {
            found_opaque_pixel = true;
          }
        }
      }
      if (!found_opaque_pixel) {
        LOG(INFO) << "Bitmap not opaque, trying to capture again";
        continue;
      }

      return result_image;
    }
  }
};

// Smoke test that ensures that when a node gets focus, the layer with the
// focus highlight actually gets drawn.
//
// Flaky on all platforms. TODO(crbug.com/40692704): Enable this test.
IN_PROC_BROWSER_TEST_F(AccessibilityFocusHighlightBrowserTest,
                       DISABLED_DrawsHighlight) {
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), GURL("data:text/html,"
                      "<body style='background-color: rgb(204, 255, 255);'>"
                      "<div tabindex=0 id='div'>Focusable div</div>")));

  AccessibilityFocusHighlight::SetNoFadeForTesting();
  AccessibilityFocusHighlight::SkipActivationCheckForTesting();
  AccessibilityFocusHighlight::UseDefaultColorForTesting();

  browser()->profile()->GetPrefs()->SetBoolean(
      prefs::kAccessibilityFocusHighlightEnabled, true);

  // The web page has a background with a specific color. Keep looping until we
  // capture an image of the page that's more than 90% that color.
  gfx::Image image;
  do {
    base::RunLoop().RunUntilIdle();
    image = CaptureWindowContents();
  } while (CountPercentPixelsWithColor(image, SkColorSetRGB(204, 255, 255)) <
           90.0f);

  BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser());
  SkColor highlight_color =
      browser_view->GetColorProvider()->GetColor(kColorFocusHighlightDefault);

  // Initially less than 0.05% of the image should be the focus ring's highlight
  // color.
  ASSERT_LT(CountPercentPixelsWithColor(image, highlight_color), 0.05f);

  // Focus something.
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  std::string script("document.getElementById('div').focus();");
  EXPECT_TRUE(content::ExecJs(web_contents, script));

  // Now wait until at least 0.1% of the image has the focus ring's highlight
  // color. If it never does, the test will time out.
  do {
    base::RunLoop().RunUntilIdle();
    image = CaptureWindowContents();
  } while (CountPercentPixelsWithColor(image, highlight_color) < 0.1f);
}

IN_PROC_BROWSER_TEST_F(AccessibilityFocusHighlightBrowserTest,
                       FocusBoundsIncludeImages) {
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), GURL("data:text/html,"
                      "<a id='link' href=''>"
                      "<img id='image' width='220' height='147' "
                      "style='vertical-align: middle;'>"
                      "</a>")));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  content::FocusChangedObserver observer(web_contents);
  std::string script("document.getElementById('link').focus();");
  ASSERT_TRUE(content::ExecJs(web_contents, script));
  auto details = observer.Wait();

  gfx::Rect bounds = details.node_bounds_in_screen;
  EXPECT_EQ(220, bounds.width());

  // Not sure where the extra px of height are coming from...
  EXPECT_EQ(147, bounds.height());
}

class ReadbackHolder : public base::RefCountedThreadSafe<ReadbackHolder> {
 public:
  ReadbackHolder() : run_loop_(std::make_unique<base::RunLoop>()) {}

  void OutputRequestCallback(std::unique_ptr<viz::CopyOutputResult> result) {
    if (result->IsEmpty()) {
      result_.reset();
    } else {
      auto scoped_sk_bitmap = result->ScopedAccessSkBitmap();
      result_ =
          std::make_unique<SkBitmap>(scoped_sk_bitmap.GetOutScopedBitmap());
      EXPECT_TRUE(result_->readyToDraw());
    }
    run_loop_->Quit();
  }

  void WaitForReadback() { run_loop_->Run(); }

  const SkBitmap& result() const { return *result_; }

 private:
  friend class base::RefCountedThreadSafe<ReadbackHolder>;

  virtual ~ReadbackHolder() = default;

  std::unique_ptr<SkBitmap> result_;
  std::unique_ptr<base::RunLoop> run_loop_;
};

const cc::ExactPixelComparator pixel_comparator;

// TODO(crbug.com/40924319): Fix flaky test on Mac.
// TODO(crbug.com/373535999): Fix flaky test on Windows.
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
#define MAYBE_FocusAppearance DISABLED_FocusAppearance
#else
#define MAYBE_FocusAppearance FocusAppearance
#endif

IN_PROC_BROWSER_TEST_F(AccessibilityFocusHighlightBrowserTest,
                       MAYBE_FocusAppearance) {
  base::ScopedAllowBlockingForTesting allow_blocking;

  AccessibilityFocusHighlight::SetNoFadeForTesting();
  AccessibilityFocusHighlight::SkipActivationCheckForTesting();

  browser()->profile()->GetPrefs()->SetBoolean(
      prefs::kAccessibilityFocusHighlightEnabled, true);

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(),
                                           GURL("data:text/html,"
                                                "<a id='link' href=''>"
                                                "<img width='10' height='10'>"
                                                "</a>")));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  content::FocusChangedObserver observer(web_contents);
  std::string script("document.getElementById('link').focus();");
  ASSERT_TRUE(content::ExecJs(web_contents, script));
  observer.Wait();
  BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser());
  AccessibilityFocusHighlight* highlight =
      browser_view->GetAccessibilityFocusHighlightForTesting();
  ui::Layer* layer = highlight->GetLayerForTesting();

  gfx::Rect source_rect = gfx::Rect(layer->size());
  scoped_refptr<ReadbackHolder> holder(new ReadbackHolder);
  std::unique_ptr<viz::CopyOutputRequest> request =
      std::make_unique<viz::CopyOutputRequest>(
          viz::CopyOutputRequest::ResultFormat::RGBA,
          viz::CopyOutputRequest::ResultDestination::kSystemMemory,
          base::BindOnce(&ReadbackHolder::OutputRequestCallback, holder));
  request->set_area(source_rect);
  layer->RequestCopyOfOutput(std::move(request));
  holder->WaitForReadback();
  SkBitmap bitmap(holder->result());
  ASSERT_FALSE(bitmap.drawsNothing());

  base::FilePath dir_test_data;
  ASSERT_TRUE(base::PathService::Get(chrome::DIR_TEST_DATA, &dir_test_data));

  std::string screenshot_filename = "focus_highlight_appearance";
  std::string platform_suffix;
#if BUILDFLAG(IS_MAC)
  platform_suffix = "_mac";
#elif BUILDFLAG(IS_WIN)
  platform_suffix = "_win";
#endif

  base::FilePath golden_filepath =
      dir_test_data.AppendASCII("accessibility")
          .AppendASCII(screenshot_filename + ".png");
  base::FilePath golden_filepath_platform =
      golden_filepath.InsertBeforeExtensionASCII(platform_suffix);
  if (base::PathExists(golden_filepath_platform)) {
    golden_filepath = golden_filepath_platform;
  }

  bool snapshot_matches =
      cc::MatchesPNGFile(bitmap, golden_filepath, pixel_comparator);
  EXPECT_TRUE(snapshot_matches);
}