-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
devtools_protocol_browsertest.cc
4013 lines (3361 loc) · 151 KB
/
devtools_protocol_browsertest.cc
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include <memory>
#include <utility>
#include "base/base64.h"
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/strings/safe_sprintf.h"
#include "base/strings/stringprintf.h"
#include "base/system/sys_info.h"
#include "base/task/sequenced_task_runner.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/values_test_util.h"
#include "base/values.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "components/download/public/common/download_file_factory.h"
#include "components/download/public/common/download_file_impl.h"
#include "components/download/public/common/download_task_runner.h"
#include "content/browser/devtools/protocol/browser_handler.h"
#include "content/browser/devtools/protocol/devtools_download_manager_delegate.h"
#include "content/browser/devtools/protocol/devtools_protocol_test_support.h"
#include "content/browser/devtools/protocol/system_info.h"
#include "content/browser/devtools/render_frame_devtools_agent_host.h"
#include "content/browser/download/download_manager_impl.h"
#include "content/browser/host_zoom_map_impl.h"
#include "content/browser/preloading/prerender/prerender_final_status.h"
#include "content/browser/renderer_host/navigator.h"
#include "content/browser/renderer_host/render_widget_host_view_base.h"
#include "content/browser/service_worker/embedded_worker_test_helper.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/javascript_dialog_manager.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/ssl_status.h"
#include "content/public/browser/tracing_controller.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/download_test_observer.h"
#include "content/public/test/no_renderer_crashes_assertion.h"
#include "content/public/test/prerender_test_util.h"
#include "content/public/test/slow_download_http_response.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/shell/browser/shell.h"
#include "content/shell/browser/shell_browser_context.h"
#include "content/shell/browser/shell_content_browser_client.h"
#include "content/shell/browser/shell_download_manager_delegate.h"
#include "net/base/features.h"
#include "net/dns/dns_test_util.h"
#include "net/dns/mock_host_resolver.h"
#include "net/dns/public/secure_dns_mode.h"
#include "net/dns/public/util.h"
#include "net/test/ssl_test_util.h"
#include "net/test/test_doh_server.h"
#include "services/tracing/public/cpp/perfetto/perfetto_config.h"
#include "services/tracing/public/cpp/tracing_features.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/blink/public/common/chrome_debug_urls.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/boringssl/src/include/openssl/nid.h"
#include "third_party/boringssl/src/include/openssl/ssl.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/layout.h"
#include "ui/compositor/compositor_switches.h"
#include "ui/display/screen.h"
#include "ui/gfx/codec/jpeg_codec.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/skia_conversions.h"
#include "ui/snapshot/snapshot.h"
#if BUILDFLAG(IS_POSIX)
#include "base/task/deferred_sequenced_task_runner.h"
#include "base/tracing/perfetto_task_runner.h"
#include "services/tracing/perfetto/system_test_utils.h"
#endif
#define EXPECT_SIZE_EQ(expected, actual) \
do { \
EXPECT_EQ((expected).width(), (actual).width()); \
EXPECT_EQ((expected).height(), (actual).height()); \
} while (false)
using testing::ElementsAre;
using testing::Eq;
namespace content {
namespace {
class TestJavaScriptDialogManager : public JavaScriptDialogManager,
public WebContentsDelegate {
public:
TestJavaScriptDialogManager() {}
TestJavaScriptDialogManager(const TestJavaScriptDialogManager&) = delete;
TestJavaScriptDialogManager& operator=(const TestJavaScriptDialogManager&) =
delete;
~TestJavaScriptDialogManager() override {}
void Handle() {
if (!callback_.is_null()) {
std::move(callback_).Run(true, std::u16string());
} else {
handle_ = true;
}
}
// WebContentsDelegate
JavaScriptDialogManager* GetJavaScriptDialogManager(
WebContents* source) override {
return this;
}
// JavaScriptDialogManager
void RunJavaScriptDialog(WebContents* web_contents,
RenderFrameHost* render_frame_host,
JavaScriptDialogType dialog_type,
const std::u16string& message_text,
const std::u16string& default_prompt_text,
DialogClosedCallback callback,
bool* did_suppress_message) override {
if (handle_) {
handle_ = false;
std::move(callback).Run(true, std::u16string());
} else {
callback_ = std::move(callback);
}
}
void RunBeforeUnloadDialog(WebContents* web_contents,
RenderFrameHost* render_frame_host,
bool is_reload,
DialogClosedCallback callback) override {}
bool HandleJavaScriptDialog(WebContents* web_contents,
bool accept,
const std::u16string* prompt_override) override {
is_handled_ = true;
return true;
}
void CancelDialogs(WebContents* web_contents,
bool reset_state) override {}
bool is_handled() { return is_handled_; }
private:
DialogClosedCallback callback_;
bool handle_ = false;
bool is_handled_ = false;
};
} // namespace
class SitePerProcessDevToolsProtocolTest : public DevToolsProtocolTest {
public:
void SetUpCommandLine(base::CommandLine* command_line) override {
DevToolsProtocolTest::SetUpCommandLine(command_line);
IsolateAllSitesForTesting(command_line);
}
};
class SyntheticKeyEventTest : public DevToolsProtocolTest {
protected:
void SendKeyEvent(const std::string& type,
int modifier,
int windowsKeyCode,
int nativeKeyCode,
const std::string& key,
bool wait) {
base::Value::Dict params;
params.Set("type", type);
params.Set("modifiers", modifier);
params.Set("windowsVirtualKeyCode", windowsKeyCode);
params.Set("nativeVirtualKeyCode", nativeKeyCode);
params.Set("key", key);
SendCommand("Input.dispatchKeyEvent", std::move(params), wait);
}
};
class PrerenderDevToolsProtocolTest : public DevToolsProtocolTest {
public:
PrerenderDevToolsProtocolTest() {
prerender_helper_ = std::make_unique<test::PrerenderTestHelper>(
base::BindRepeating(&PrerenderDevToolsProtocolTest::web_contents,
base::Unretained(this)));
}
GURL GetUrl(const std::string& path) {
return embedded_test_server()->GetURL("a.test", path);
}
bool HasHostForUrl(const GURL& url) {
int host_id = prerender_helper_->GetHostForUrl(url);
return host_id != RenderFrameHost::kNoFrameTreeNodeId;
}
int AddPrerender(const GURL& prerendering_url) {
return prerender_helper_->AddPrerender(prerendering_url);
}
RenderFrameHostImpl* GetPrerenderedMainFrameHost(int host_id) {
return static_cast<RenderFrameHostImpl*>(
prerender_helper_->GetPrerenderedMainFrameHost(host_id));
}
void NavigatePrimaryPage(const GURL& url) {
prerender_helper_->NavigatePrimaryPage(url);
}
// WebContentsDelegate overrides.
bool IsPrerender2Supported(WebContents& web_contents) override {
return true;
}
WebContents* web_contents() const { return shell()->web_contents(); }
private:
std::unique_ptr<test::PrerenderTestHelper> prerender_helper_;
};
class PrerenderHoldbackDevToolsProtocolTest
: public PrerenderDevToolsProtocolTest {
public:
PrerenderHoldbackDevToolsProtocolTest() {
feature_list_.InitAndEnableFeature(features::kPrerender2Holdback);
}
private:
base::test::ScopedFeatureList feature_list_;
};
class PreloadingHoldbackDevToolsProtocolTest
: public PrerenderDevToolsProtocolTest {
public:
PreloadingHoldbackDevToolsProtocolTest() {
feature_list_.InitAndEnableFeature(features::kPreloadingHoldback);
}
private:
base::test::ScopedFeatureList feature_list_;
};
class MultiplePrerendersDevToolsProtocolTest
: public PrerenderDevToolsProtocolTest {
public:
MultiplePrerendersDevToolsProtocolTest() = default;
private:
test::ScopedPrerenderFeatureList prerender_feature_list_;
};
class SyntheticMouseEventTest : public DevToolsProtocolTest {
public:
SyntheticMouseEventTest() {
// On Android, zoom level is set to 0 in
// WebContentsImpl::GetPendingPageZoomLevel unless the kAccessibilityPageZoom
// feature is enabled. We enable it to be able to test mouse events across all
// platforms.
#if BUILDFLAG(IS_ANDROID)
feature_list_.InitAndEnableFeature(features::kAccessibilityPageZoom);
#endif
}
protected:
void SendMouseEvent(const std::string& type,
int x,
int y,
const std::string& button,
bool wait) {
base::Value::Dict params;
params.Set("type", type);
params.Set("x", x);
params.Set("y", y);
if (!button.empty()) {
params.Set("button", button);
params.Set("clickCount", 1);
}
SendCommand("Input.dispatchMouseEvent", std::move(params), wait);
}
void InitMouseDownLog() {
ASSERT_TRUE(
content::ExecJs(shell()->web_contents(),
"logs = []; window.addEventListener('mousedown', e => "
"logs.push(`${e.type},${e.clientX},${e.clientY}`));"));
}
std::string GetMouseDownLog() {
return content::EvalJs(shell()->web_contents(), "window.logs.join(';')")
.ExtractString();
}
private:
base::test::ScopedFeatureList feature_list_;
};
IN_PROC_BROWSER_TEST_F(SyntheticKeyEventTest, KeyEventSynthesizeKey) {
NavigateToURLBlockUntilNavigationsComplete(shell(), GURL("about:blank"), 1);
Attach();
ASSERT_TRUE(content::ExecJs(
shell()->web_contents(),
"function handleKeyEvent(event) {"
"domAutomationController.send(event.key);"
"}"
"document.body.addEventListener('keydown', handleKeyEvent);"
"document.body.addEventListener('keyup', handleKeyEvent);"));
DOMMessageQueue dom_message_queue(shell()->web_contents());
// Send enter (keycode 13).
SendKeyEvent("rawKeyDown", 0, 13, 13, "Enter", true);
SendKeyEvent("keyUp", 0, 13, 13, "Enter", true);
std::string key;
ASSERT_TRUE(dom_message_queue.WaitForMessage(&key));
EXPECT_EQ("\"Enter\"", key);
ASSERT_TRUE(dom_message_queue.WaitForMessage(&key));
EXPECT_EQ("\"Enter\"", key);
// Send escape (keycode 27).
SendKeyEvent("rawKeyDown", 0, 27, 27, "Escape", true);
SendKeyEvent("keyUp", 0, 27, 27, "Escape", true);
ASSERT_TRUE(dom_message_queue.WaitForMessage(&key));
EXPECT_EQ("\"Escape\"", key);
ASSERT_TRUE(dom_message_queue.WaitForMessage(&key));
EXPECT_EQ("\"Escape\"", key);
}
// Flaky: https://crbug.com/889878
IN_PROC_BROWSER_TEST_F(SyntheticKeyEventTest, DISABLED_KeyboardEventAck) {
NavigateToURLBlockUntilNavigationsComplete(shell(), GURL("about:blank"), 1);
Attach();
ASSERT_TRUE(content::ExecJs(
shell()->web_contents(),
"document.body.addEventListener('keydown', () => {debugger;});"));
auto filter = std::make_unique<InputMsgWatcher>(
RenderWidgetHostImpl::From(shell()
->web_contents()
->GetPrimaryMainFrame()
->GetRenderViewHost()
->GetWidget()),
blink::WebInputEvent::Type::kRawKeyDown);
SendCommandSync("Debugger.enable");
SendKeyEvent("rawKeyDown", 0, 13, 13, "Enter", false);
// We expect that the debugger message event arrives *before* the input
// event ack, and the subsequent command response for Input.dispatchKeyEvent.
WaitForNotification("Debugger.paused");
EXPECT_FALSE(filter->HasReceivedAck());
EXPECT_EQ(1, received_responses_count());
SendCommandSync("Debugger.resume");
filter->WaitForAck();
EXPECT_EQ(3, received_responses_count());
}
// Flaky: https://crbug.com/1263461
IN_PROC_BROWSER_TEST_F(SyntheticMouseEventTest, DISABLED_MouseEventAck) {
NavigateToURLBlockUntilNavigationsComplete(shell(), GURL("about:blank"), 1);
Attach();
ASSERT_TRUE(content::ExecJs(
shell()->web_contents(),
"document.body.addEventListener('mousedown', () => {debugger;});"));
auto filter = std::make_unique<InputMsgWatcher>(
RenderWidgetHostImpl::From(shell()
->web_contents()
->GetPrimaryMainFrame()
->GetRenderViewHost()
->GetWidget()),
blink::WebInputEvent::Type::kMouseDown);
SendCommandSync("Debugger.enable");
SendMouseEvent("mousePressed", 15, 15, "left", false);
// We expect that the debugger message event arrives *before* the input
// event ack, and the subsequent command response for
// Input.dispatchMouseEvent.
WaitForNotification("Debugger.paused");
EXPECT_FALSE(filter->HasReceivedAck());
EXPECT_EQ(1, received_responses_count());
SendCommandSync("Debugger.resume");
filter->WaitForAck();
EXPECT_EQ(3, received_responses_count());
}
IN_PROC_BROWSER_TEST_F(SyntheticMouseEventTest, MouseEventCoordinates) {
ASSERT_TRUE(embedded_test_server()->Start());
GURL test_url = embedded_test_server()->GetURL("/devtools/zoom.html");
NavigateToURLBlockUntilNavigationsComplete(shell(), test_url, 1);
Attach();
InitMouseDownLog();
// In about 1 out of 1000 runs, the event gets lost on the way to the
// renderer. We repeat the event dispatch until it succeeds since we want to
// test event coordinates.
while (GetMouseDownLog() == "") {
SendMouseEvent("mousePressed", 15, 15, "left", true);
}
ASSERT_EQ("mousedown,15,15", GetMouseDownLog());
}
IN_PROC_BROWSER_TEST_F(SyntheticMouseEventTest, MouseEventCoordinatesWithZoom) {
ASSERT_TRUE(embedded_test_server()->Start());
GURL test_url = embedded_test_server()->GetURL("/devtools/zoom.html");
NavigateToURLBlockUntilNavigationsComplete(shell(), test_url, 1);
Attach();
SendCommandSync("Page.enable");
InitMouseDownLog();
HostZoomMap* host_zoom_map =
HostZoomMap::GetForWebContents(shell()->web_contents());
host_zoom_map->SetZoomLevelForHost(test_url.host(),
blink::PageZoomFactorToZoomLevel(2.5));
WaitForNotification("Page.frameResized", true);
// In about 1 out of 1000 runs, the event gets lost on the way to the
// renderer. We repeat the event dispatch until it succeeds since we want to
// test event coordinates.
while (GetMouseDownLog() == "") {
SendMouseEvent("mousePressed", 15, 15, "left", true);
}
ASSERT_EQ("mousedown,15,15", GetMouseDownLog());
}
namespace {
bool DecodePNG(std::string base64_data, SkBitmap* bitmap) {
std::string png_data;
if (!base::Base64Decode(base64_data, &png_data))
return false;
return gfx::PNGCodec::Decode(
reinterpret_cast<unsigned const char*>(png_data.data()), png_data.size(),
bitmap);
}
std::unique_ptr<SkBitmap> DecodeJPEG(std::string base64_data) {
std::string jpeg_data;
if (!base::Base64Decode(base64_data, &jpeg_data))
return nullptr;
return gfx::JPEGCodec::Decode(
reinterpret_cast<unsigned const char*>(jpeg_data.data()),
jpeg_data.size());
}
int ColorsSquareDiff(SkColor color1, SkColor color2) {
auto a_diff = static_cast<int>(SkColorGetA(color1)) -
static_cast<int>(SkColorGetA(color2));
auto r_diff = static_cast<int>(SkColorGetR(color1)) -
static_cast<int>(SkColorGetR(color2));
auto g_diff = static_cast<int>(SkColorGetG(color1)) -
static_cast<int>(SkColorGetG(color2));
auto b_diff = static_cast<int>(SkColorGetB(color1)) -
static_cast<int>(SkColorGetB(color2));
return a_diff * a_diff + r_diff * r_diff + g_diff * g_diff +
b_diff * b_diff;
}
bool ColorsMatchWithinLimit(SkColor color1, SkColor color2, int max_collor_diff) {
return ColorsSquareDiff(color1, color2) <= max_collor_diff * max_collor_diff;
}
// Adapted from cc::ExactPixelComparator.
bool MatchesBitmap(const SkBitmap& expected_bmp,
const SkBitmap& actual_bmp,
const gfx::Rect& matching_mask,
float device_scale_factor,
int max_collor_diff) {
// Number of pixels with an error
int error_pixels_count = 0;
gfx::Rect error_bounding_rect = gfx::Rect();
// Scale expectations along with the mask.
device_scale_factor = device_scale_factor ? device_scale_factor : 1;
// Check that bitmaps have identical dimensions.
int expected_width = round(expected_bmp.width() * device_scale_factor);
int expected_height = round(expected_bmp.height() * device_scale_factor);
EXPECT_EQ(expected_width, actual_bmp.width());
EXPECT_EQ(expected_height, actual_bmp.height());
if (expected_width != actual_bmp.width() ||
expected_height != actual_bmp.height()) {
return false;
}
DCHECK(gfx::SkIRectToRect(actual_bmp.bounds()).Contains(matching_mask));
for (int x = matching_mask.x(); x < matching_mask.right(); ++x) {
for (int y = matching_mask.y(); y < matching_mask.bottom(); ++y) {
SkColor actual_color =
actual_bmp.getColor(x * device_scale_factor, y * device_scale_factor);
SkColor expected_color = expected_bmp.getColor(x, y);
if (!ColorsMatchWithinLimit(actual_color, expected_color, max_collor_diff)) {
if (error_pixels_count < 10) {
LOG(ERROR) << "Pixel (" << x << "," << y
<< "). Expected: " << std::hex << expected_color
<< ", actual: " << actual_color << std::dec
<< ", square diff: " << ColorsSquareDiff(expected_color, actual_color);
}
error_pixels_count++;
error_bounding_rect.Union(gfx::Rect(x, y, 1, 1));
}
}
}
if (error_pixels_count != 0) {
LOG(ERROR) << "Number of pixel with an error: " << error_pixels_count;
LOG(ERROR) << "Error Bounding Box : " << error_bounding_rect.ToString();
return false;
}
return true;
}
} // namespace
enum class ScreenshotEncoding { PNG, JPEG, WEBP };
std::string EncodingEnumToString(ScreenshotEncoding encoding) {
switch (encoding) {
case ScreenshotEncoding::PNG:
return "png";
case ScreenshotEncoding::JPEG:
return "jpeg";
case ScreenshotEncoding::WEBP:
return "webp";
default:
return "";
}
}
class CaptureScreenshotTest : public DevToolsProtocolTest {
protected:
std::unique_ptr<SkBitmap> CaptureScreenshot(
ScreenshotEncoding encoding,
bool from_surface,
const gfx::RectF& clip = gfx::RectF(),
float clip_scale = 0,
bool capture_beyond_viewport = false,
bool expect_error = false) {
base::Value::Dict params;
params.Set("format", EncodingEnumToString(encoding));
params.Set("quality", 100);
params.Set("fromSurface", from_surface);
if (capture_beyond_viewport) {
params.Set("captureBeyondViewport", true);
}
if (clip_scale) {
base::Value::Dict clip_value;
clip_value.Set("x", clip.x());
clip_value.Set("y", clip.y());
clip_value.Set("width", clip.width());
clip_value.Set("height", clip.height());
clip_value.Set("scale", clip_scale);
params.Set("clip", std::move(clip_value));
}
SendCommandSync("Page.captureScreenshot", std::move(params));
std::unique_ptr<SkBitmap> result_bitmap;
if (expect_error && error()) {
EXPECT_THAT(error()->FindInt("code"),
testing::Optional(
static_cast<int>(crdtp::DispatchCode::SERVER_ERROR)));
} else {
const std::string* base64 = result()->FindString("data");
if (encoding == ScreenshotEncoding::PNG) {
result_bitmap = std::make_unique<SkBitmap>();
EXPECT_TRUE(DecodePNG(*base64, result_bitmap.get()));
} else if (encoding == ScreenshotEncoding::JPEG) {
result_bitmap = DecodeJPEG(*base64);
} else {
// Decode not implemented.
}
EXPECT_TRUE(result_bitmap);
}
return result_bitmap;
}
void CaptureScreenshotAndCompareTo(const SkBitmap& expected_bitmap,
ScreenshotEncoding encoding,
bool from_surface,
float device_scale_factor = 0,
const gfx::RectF& clip = gfx::RectF(),
float clip_scale = 0,
bool capture_beyond_viewport = false) {
std::unique_ptr<SkBitmap> result_bitmap = CaptureScreenshot(
encoding, from_surface, clip, clip_scale, capture_beyond_viewport);
gfx::Rect matching_mask(gfx::SkIRectToRect(expected_bitmap.bounds()));
#if BUILDFLAG(IS_MAC)
// Mask out the corners, which may be drawn differently on Mac because of
// rounded corners.
matching_mask.Inset(4);
#endif
// A color profile can be installed on the host that could affect
// pixel colors. Also JPEG compression could further distort the color.
// Allow some error between actual and expected pixel values.
// That assumes there is no shift in pixel positions, so it only works
// reliably if all pixels have equal values.
int max_collor_diff = 20;
EXPECT_TRUE(MatchesBitmap(expected_bitmap, *result_bitmap, matching_mask,
device_scale_factor, max_collor_diff));
}
gfx::Size GetPageContentSize() {
const base::Value::Dict* content_size =
SendCommandSync("Page.getLayoutMetrics")->FindDict("cssContentSize");
return gfx::Size(content_size->FindInt("width").value(),
content_size->FindInt("height").value());
}
// We compare against the actual physical backing size rather than the
// view size, because the view size is stored adjusted for DPI and only in
// integer precision.
gfx::Size GetViewSize() {
return static_cast<RenderWidgetHostViewBase*>(
shell()->web_contents()->GetRenderWidgetHostView())
->GetCompositorViewportPixelSize();
}
// We compare the bitmap with the captured screenshot to verify the
// size and color of the screenshot.
SkBitmap GenerateBitmap(gfx::Size size, SkColor color) {
SkBitmap expected_bitmap;
expected_bitmap.allocN32Pixels(size.width(), size.height());
expected_bitmap.eraseColor(color);
return expected_bitmap;
}
void SetDefaultBackgroundColorOverride(int r, int g, int b, float a) {
auto params = base::Value::Dict();
base::Value::Dict color;
color.Set("r", r);
color.Set("g", g);
color.Set("b", b);
color.Set("a", a);
params.Set("color", std::move(color));
SendCommandSync("Emulation.setDefaultBackgroundColorOverride",
std::move(params));
}
void SetDeviceMetricsOverride(int width,
int height,
float device_scale_factor,
bool mobile,
absl::optional<bool> fitWindow) {
auto params = base::Value::Dict();
params.Set("width", width);
params.Set("height", height);
params.Set("deviceScaleFactor", device_scale_factor);
params.Set("mobile", mobile);
if (fitWindow.has_value()) {
params.Set("fitWindow", fitWindow.value());
}
SendCommandSync("Emulation.setDeviceMetricsOverride", std::move(params));
}
// Takes a screenshot of a colored box that is positioned inside the frame.
void PlaceAndCaptureBox(const gfx::Size& frame_size,
const gfx::Size& box_size,
float screenshot_scale,
float device_scale_factor) {
static const int kBoxOffsetHeight = 100;
const gfx::Size scaled_box_size =
ScaleToFlooredSize(box_size, screenshot_scale);
base::Value::Dict params;
VLOG(1) << "Testing screenshot of box with size " << box_size.width() << "x"
<< box_size.height() << "px at scale " << screenshot_scale
<< " ...";
// Draw a blue box of provided size in the horizontal center of the page.
EXPECT_TRUE(content::ExecJs(
shell()->web_contents(),
base::StringPrintf(
"var style = document.body.style; "
"style.overflow = 'hidden'; "
"style.minHeight = '%dpx'; "
"style.backgroundImage = 'linear-gradient(#0000ff, #0000ff)'; "
"style.backgroundSize = '%dpx %dpx'; "
"style.backgroundPosition = '50%% %dpx'; "
"style.backgroundRepeat = 'no-repeat'; ",
box_size.height() + kBoxOffsetHeight, box_size.width(),
box_size.height(), kBoxOffsetHeight)));
// Force frame size: The offset of the blue box within the frame shouldn't
// change during screenshotting. This verifies that the page doesn't observe
// a change in frame size as a side effect of screenshotting.
SetDeviceMetricsOverride(frame_size.width(), frame_size.height(),
device_scale_factor, false, absl::nullopt);
// Resize frame to scaled blue box size.
gfx::RectF clip;
clip.set_width(box_size.width());
clip.set_height(box_size.height());
clip.set_x((frame_size.width() - box_size.width()) / 2.);
clip.set_y(kBoxOffsetHeight);
// Capture screenshot and verify that it is indeed blue.
SkBitmap expected_bitmap =
GenerateBitmap(scaled_box_size, SkColorSetRGB(0x00, 0x00, 0xff));
// If the device scale factor is 0,
// get the original device scale factor to compare with
if (!device_scale_factor) {
device_scale_factor = display::Screen::GetScreen()
->GetPrimaryDisplay()
.device_scale_factor();
}
CaptureScreenshotAndCompareTo(expected_bitmap, ScreenshotEncoding::PNG,
/*from_surface=*/true, device_scale_factor,
clip, screenshot_scale);
// Reset for next screenshot.
SendCommandSync("Emulation.clearDeviceMetricsOverride");
}
bool IsTrusted() override { return is_trusted_; }
bool is_trusted_ = true;
private:
#if !BUILDFLAG(IS_ANDROID)
void SetUp() override {
EnablePixelOutput();
DevToolsProtocolTest::SetUp();
}
#endif
};
IN_PROC_BROWSER_TEST_F(CaptureScreenshotTest,
CaptureScreenshotBeyondViewport_OutOfView) {
// TODO(crbug.com/653637) This test fails consistently on low-end Android
// devices.
if (base::SysInfo::IsLowEndDevice())
return;
// Load dummy page before getting the view size.
shell()->LoadURL(GURL("data:text/html,"));
gfx::Size view_size = GetViewSize();
// Make a page a bit bigger than the view to force scrollbars to be shown.
shell()->LoadURL(
GURL(base::StringPrintf("data:text/html,"
R"(<body style='background:%%23123456;height:%dpx;
width:%dpx'></body>)",
/*content_height*/ view_size.height() + 10,
/*content_width*/ view_size.width() + 10)));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
Attach();
// Generate expected screenshot without any scrollbars.
gfx::Size actual_page_size = GetPageContentSize();
SkBitmap expected_bitmap =
GenerateBitmap(actual_page_size, SkColorSetRGB(0x12, 0x34, 0x56));
float device_scale_factor =
display::Screen::GetScreen()->GetPrimaryDisplay().device_scale_factor();
// Verify there are no scrollbars on the screenshot.
CaptureScreenshotAndCompareTo(
expected_bitmap, ScreenshotEncoding::PNG, /*from_surface=*/true,
device_scale_factor,
/*clip=*/
gfx::RectF(0, 0, actual_page_size.width(), actual_page_size.height()),
/*clip_scale=*/1, true);
CaptureScreenshotAndCompareTo(expected_bitmap, ScreenshotEncoding::PNG,
/*from_surface=*/true, device_scale_factor,
/*clip=*/gfx::RectF(), /*clip_scale=*/0,
/*capture_beyond_viewport=*/true);
}
IN_PROC_BROWSER_TEST_F(CaptureScreenshotTest,
CaptureScreenshotBeyondViewport_IFrame) {
// TODO(crbug.com/653637) This test fails consistently on low-end Android
// devices.
if (base::SysInfo::IsLowEndDevice())
return;
// Load dummy page before getting the view size.
shell()->LoadURL(GURL("data:text/html,"));
gfx::Size view_size = GetViewSize();
// Make a page a bit bigger than the view to force scrollbars to be shown.
int content_height = view_size.height() + 50;
int content_width = view_size.width() + 50;
int margin = 100;
shell()->LoadURL(
GURL(base::StringPrintf("data:text/html,"
R"(
<body style=' height:%dpx;
width:%dpx;'>
<iframe style=" height:%dpx;
width:%dpx;
background:%%23123456;
border:none;">
</iframe></body>
)",
content_height + margin, content_width + margin,
content_height, content_width)));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
Attach();
// Generate expected screenshot without any scrollbars.
SkBitmap expected_bitmap =
GenerateBitmap(gfx::Size(content_width, content_height),
SkColorSetRGB(0x12, 0x34, 0x56));
float device_scale_factor =
display::Screen::GetScreen()->GetPrimaryDisplay().device_scale_factor();
// Verify there are no scrollbars on the screenshot.
// Even if margin is 0 then the iframe appears 8px away from beginning of the
// page
CaptureScreenshotAndCompareTo(
expected_bitmap, ScreenshotEncoding::PNG, /*from_surface=*/true,
device_scale_factor,
/*clip=*/gfx::RectF(8, 8, content_width, content_height),
/*clip_scale=*/1, /*capture_beyond_viewport=*/true);
}
// ChromeOS and Android has fading out scrollbars, which makes the test flacky.
// TODO(crbug.com/1150059) Android has a problem with changing scale.
// TODO(crbug.com/1147911) Android Lollipop has a problem with capturing
// screenshot.
// TODO(crbug.com/1156767) Flaky on linux-lacros-tester-rel
// TODO(crbug.com/1286261): Failing on MacOS.
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS_ASH) || \
BUILDFLAG(IS_CHROMEOS_LACROS) || BUILDFLAG(IS_MAC)
#define MAYBE_CaptureScreenshotBeyondViewport_InnerScrollbarsAreShown \
DISABLED_CaptureScreenshotBeyondViewport_InnerScrollbarsAreShown
#else
#define MAYBE_CaptureScreenshotBeyondViewport_InnerScrollbarsAreShown \
CaptureScreenshotBeyondViewport_InnerScrollbarsAreShown
#endif
IN_PROC_BROWSER_TEST_F(
CaptureScreenshotTest,
MAYBE_CaptureScreenshotBeyondViewport_InnerScrollbarsAreShown) {
// TODO(crbug.com/653637) This test fails consistently on low-end Android
// devices.
if (base::SysInfo::IsLowEndDevice())
return;
shell()->LoadURL(GURL(
"data:text/html,<body><div style='width: 50px; height: 50px; overflow: "
"scroll;'><h3>test</h3><h3>test</h3><h3>test</h3></div></body>"));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
Attach();
gfx::Size view_size = GetViewSize();
// Capture a screenshot not "from surface", meaning without emulation and
// without changing preferences, as-is.
std::unique_ptr<SkBitmap> expected_bitmap =
CaptureScreenshot(ScreenshotEncoding::PNG, false);
float device_scale_factor =
display::Screen::GetScreen()->GetPrimaryDisplay().device_scale_factor();
// Compare the captured screenshot with one made "from_surface", where actual
// scrollbar magic happened, and verify it looks the same, meaning the
// internal scrollbars are rendered.
CaptureScreenshotAndCompareTo(
*expected_bitmap, ScreenshotEncoding::PNG, /*from_surface=*/true,
device_scale_factor,
/*clip=*/gfx::RectF(0, 0, view_size.width(), view_size.height()),
/*clip_scale=*/1, /*capture_beyond_viewport=*/true);
}
// ChromeOS and Android don't support software compositing.
#if !BUILDFLAG(IS_CHROMEOS_ASH) && !BUILDFLAG(IS_ANDROID)
class NoGPUCaptureScreenshotTest : public CaptureScreenshotTest {
void SetUpCommandLine(base::CommandLine* command_line) override {
CaptureScreenshotTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kDisableGpuCompositing);
}
};
// Tests that large screenshots are composited fine with software compositor.
// Regression test for https://crbug.com/1137291.
// Flaky on Linux. http://crbug.com/1301176
#if BUILDFLAG(IS_LINUX)
#define MAYBE_LargeScreenshot DISABLED_LargeScreenshot
#else
#define MAYBE_LargeScreenshot LargeScreenshot
#endif
IN_PROC_BROWSER_TEST_F(NoGPUCaptureScreenshotTest, MAYBE_LargeScreenshot) {
// This test fails consistently on low-end Android devices.
// See crbug.com/653637.
// TODO(eseckler): Reenable with error limit if necessary.
if (base::SysInfo::IsLowEndDevice())
return;
// If disabling software compositing is disabled by the test caller,
// we're out of luck.
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableSoftwareCompositingFallback)) {
return;
}
shell()->LoadURL(
GURL("data:text/html,"
"<style>body,html { padding: 0; margin: 0; }</style>"
"<div style='width: 1250px; height: 8440px; "
" background: linear-gradient(red, blue)'></div>"));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
Attach();
SetDeviceMetricsOverride(/*width=*/1280, /*height=*/8440,
/*device_scale_factor=*/1,
/*mobile=*/false,
/*fitWindow=*/absl::nullopt);
auto bitmap = CaptureScreenshot(ScreenshotEncoding::PNG, true,
gfx::RectF(0, 0, 1280, 8440), 1);
SendCommandSync("Emulation.clearDeviceMetricsOverride");
EXPECT_EQ(1280, bitmap->width());
EXPECT_EQ(8440, bitmap->height());
// Top-left is red-ish.
SkColor top_left = bitmap->getColor(0, 0);
EXPECT_GT(static_cast<int>(SkColorGetR(top_left)), 128);
EXPECT_LT(static_cast<int>(SkColorGetB(top_left)), 128);
// Bottom-left is blue-ish.
SkColor bottom_left = bitmap->getColor(0, 8339);
EXPECT_LT(static_cast<int>(SkColorGetR(bottom_left)), 128);
EXPECT_GT(static_cast<int>(SkColorGetB(bottom_left)), 128);
}
#endif // !BUILDFLAG(IS_CHROMEOS_ASH) && !BUILDFLAG(IS_ANDROID)
// Setting frame size (through RWHV) is not supported on Android.
// This test seems to be very flaky on all platforms: https://crbug.com/801173
IN_PROC_BROWSER_TEST_F(CaptureScreenshotTest, DISABLED_CaptureScreenshotArea) {
static const gfx::Size kFrameSize(800, 600);
shell()->LoadURL(GURL("about:blank"));
Attach();
// Test capturing a subarea inside the emulated frame at different scales.
PlaceAndCaptureBox(kFrameSize, gfx::Size(100, 200), 1.0, 1.);
PlaceAndCaptureBox(kFrameSize, gfx::Size(100, 200), 2.0, 1.);
PlaceAndCaptureBox(kFrameSize, gfx::Size(100, 200), 0.5, 1.);
// Check non-1 device scale factor.
PlaceAndCaptureBox(kFrameSize, gfx::Size(100, 200), 1.0, 2.);
// Ensure not emulating device scale factor works.
PlaceAndCaptureBox(kFrameSize, gfx::Size(100, 200), 1.0, 0.);
}
// Verifies that setDefaultBackgroundColorOverride changes the background color
// of a page that does not specify one.
IN_PROC_BROWSER_TEST_F(CaptureScreenshotTest,
SetDefaultBackgroundColorOverride) {
if (base::SysInfo::IsLowEndDevice())
return;
shell()->LoadURL(GURL("about:blank"));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
Attach();
SetDefaultBackgroundColorOverride(/*r=*/0x00, /*g=*/0x00, /*b=*/0xff,
/*a=*/1.0);
gfx::Size view_size = GetViewSize();
SkBitmap expected_bitmap =
GenerateBitmap(view_size, SkColorSetRGB(0x00, 0x00, 0xff));