File: render_widget_host_view_mac_browsertest.mm

package info (click to toggle)
chromium 142.0.7444.175-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,303,984 kB
  • sloc: cpp: 35,488,370; ansic: 7,479,680; javascript: 4,259,373; python: 1,466,844; xml: 757,444; asm: 710,716; pascal: 187,980; sh: 89,247; perl: 88,690; objc: 79,984; sql: 56,984; cs: 42,192; fortran: 24,137; makefile: 22,919; tcl: 15,277; php: 14,018; yacc: 9,005; ruby: 7,553; awk: 3,720; lisp: 3,096; lex: 1,330; ada: 727; jsp: 228; sed: 36
file content (574 lines) | stat: -rw-r--r-- 20,033 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
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
// 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 "content/browser/renderer_host/render_widget_host_view_mac.h"

#import <Carbon/Carbon.h>

#include <string>
#include <string_view>

#include "base/functional/bind.h"
#import "base/mac/mac_util.h"
#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/run_until.h"
#include "base/test/scoped_feature_list.h"
#import "content/app_shim_remote_cocoa/render_widget_host_view_cocoa.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_features.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/shell/browser/shell.h"
#include "third_party/blink/public/platform/web_text_input_type.h"
#include "ui/events/test/cocoa_test_event_utils.h"

@interface TextInputFlagChangeWaiter : NSObject
@end

@implementation TextInputFlagChangeWaiter {
  RenderWidgetHostViewCocoa* _rwhv_cocoa;
  std::unique_ptr<base::RunLoop> _run_loop;
}

- (instancetype)initWithRenderWidgetHostViewCocoa:
    (RenderWidgetHostViewCocoa*)rwhv_cocoa {
  if ((self = [super init])) {
    _rwhv_cocoa = rwhv_cocoa;
    [_rwhv_cocoa addObserver:self
                  forKeyPath:@"textInputFlags"
                     options:NSKeyValueObservingOptionNew
                     context:nullptr];
    [self reset];
  }
  return self;
}

- (void)dealloc {
  [_rwhv_cocoa removeObserver:self forKeyPath:@"textInputFlags"];
}

- (void)reset {
  _run_loop = std::make_unique<base::RunLoop>();
}

- (void)wait {
  _run_loop->Run();

  [self reset];
}

- (void)observeValueForKeyPath:(NSString*)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSKeyValueChangeKey, id>*)change
                       context:(void*)context {
  _run_loop->Quit();
}
@end

@interface FakeTextCheckingResult : NSTextCheckingResult <NSCopying>
@property(readonly) NSRange range;
@property(readonly) NSString* replacementString;
@property(readonly) NSTextCheckingType resultType;
@end

@implementation FakeTextCheckingResult

@synthesize range = _range;
@synthesize replacementString = _replacementString;
@synthesize resultType = _resultType;

+ (FakeTextCheckingResult*)resultWithRange:(NSRange)range
                         replacementString:(NSString*)replacementString {
  FakeTextCheckingResult* result = [[FakeTextCheckingResult alloc] init];
  result->_range = range;
  result->_replacementString = replacementString;
  result->_resultType = NSTextCheckingTypeReplacement;
  return result;
}

- (NSString*)replacementString {
  return _replacementString;
}

- (NSTextCheckingResult*)resultByAdjustingRangesWithOffset:(NSInteger)offset {
  NSRange adjustedRange = NSMakeRange(_range.location + offset, _range.length);
  return [FakeTextCheckingResult resultWithRange:adjustedRange
                               replacementString:_replacementString];
}

@end

@interface FakeSpellChecker : NSObject
@property(strong) void (^correctionCompletionHandler)(NSString*);
@property(strong) NSString* acceptedString;
- (void)waitForCheckString;
- (void)reset;
@end

@implementation FakeSpellChecker {
  std::unique_ptr<base::RunLoop> _run_loop;
}

@synthesize correctionCompletionHandler = _correctionCompletionHandler;
@synthesize acceptedString = _acceptedString;

- (instancetype)init {
  if (self = [super init]) {
    [self reset];
  }
  return self;
}

- (void)reset {
  _run_loop = std::make_unique<base::RunLoop>();
}

- (void)waitForCheckString {
  _run_loop->Run();
  [self reset];
}

// Mock spell checker that provides text replacement "omw" -> "On my way".
- (NSArray<NSTextCheckingResult*>*)
               checkString:(NSString*)stringToCheck
                     range:(NSRange)range
                     types:(NSTextCheckingTypes)checkingTypes
                   options:(nullable NSDictionary<NSTextCheckingOptionKey, id>*)
                               options
    inSpellDocumentWithTag:(NSInteger)tag
               orthography:(NSOrthography**)orthography
                 wordCount:(NSInteger*)wordCount {
  if (_run_loop) {
    _run_loop->Quit();
  }

  NSRange omwRange = [stringToCheck rangeOfString:@"omw"];
  if (omwRange.location != NSNotFound) {
    FakeTextCheckingResult* fakeResult =
        [FakeTextCheckingResult resultWithRange:omwRange
                              replacementString:@"On my way"];
    return @[ static_cast<NSTextCheckingResult*>(fakeResult) ];
  }
  return @[];
}

- (void)showCorrectionIndicatorOfType:(NSCorrectionIndicatorType)type
                        primaryString:(NSString*)primaryString
                   alternativeStrings:(NSArray<NSString*>*)alternativeStrings
                      forStringInRect:(NSRect)rect
                                 view:(NSView*)view
                    completionHandler:(void (^)(NSString*))completionHandler {
  self.correctionCompletionHandler = completionHandler;
  self.acceptedString = primaryString;
}

- (void)dismissCorrectionIndicatorForView:(NSView*)view {
  // Call the completion handler with the accepted string when dismissed
  if (self.correctionCompletionHandler) {
    self.correctionCompletionHandler(self.acceptedString);
    self.correctionCompletionHandler = nil;
    self.acceptedString = nil;
  }
}

- (BOOL)preventsAutocorrectionBeforeString:(NSString*)string
                                  language:(NSString*)language {
  return NO;
}

@end

namespace content {

namespace {

class TextCallbackWaiter {
 public:
  TextCallbackWaiter() = default;

  TextCallbackWaiter(const TextCallbackWaiter&) = delete;
  TextCallbackWaiter& operator=(const TextCallbackWaiter&) = delete;

  void Wait() { run_loop_.Run(); }

  const std::u16string& text() const { return text_; }

  void GetText(std::u16string_view text) {
    text_ = std::u16string(text);
    run_loop_.Quit();
  }

 private:
  std::u16string text_;
  base::RunLoop run_loop_;
};

class TextSelectionWaiter : public TextInputManager::Observer {
 public:
  explicit TextSelectionWaiter(RenderWidgetHostViewMac* rwhv,
                               int expected_changes = 1)
      : expected_changes_(expected_changes), observed_changes_(0) {
    rwhv->GetTextInputManager()->AddObserver(this);
  }

  void OnTextSelectionChanged(TextInputManager* text_input_manager,
                              RenderWidgetHostViewBase* updated_view) override {
    observed_changes_++;
    if (observed_changes_ >= expected_changes_) {
      text_input_manager->RemoveObserver(this);
      run_loop_.Quit();
    }
  }

  void Wait() { run_loop_.Run(); }

 private:
  base::RunLoop run_loop_;
  int expected_changes_;
  int observed_changes_;
};

}  // namespace

class RenderWidgetHostViewMacTest : public ContentBrowserTest {
 public:
  RenderWidgetHostViewMacTest() {
    scoped_feature_list_.InitAndEnableFeature(
        features::kSonomaAccessibilityActivationRefinements);
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
};

IN_PROC_BROWSER_TEST_F(RenderWidgetHostViewMacTest, GetPageTextForSpeech) {
  GURL url(
      "data:text/html,<span>Hello</span>"
      "<span style='display:none'>Goodbye</span>"
      "<span>World</span>");
  EXPECT_TRUE(NavigateToURL(shell(), url));

  RenderWidgetHostView* rwhv =
      shell()->web_contents()->GetPrimaryMainFrame()->GetView();
  RenderWidgetHostViewMac* rwhv_mac =
      static_cast<RenderWidgetHostViewMac*>(rwhv);

  TextCallbackWaiter waiter;
  rwhv_mac->GetPageTextForSpeech(
      base::BindOnce(&TextCallbackWaiter::GetText, base::Unretained(&waiter)));
  waiter.Wait();

  EXPECT_EQ(u"Hello\nWorld", waiter.text());
}

// Test that -firstRectForCharacterRange:actualRange: works when the range
// isn't in the active selection, which requires a sync IPC to the renderer.
IN_PROC_BROWSER_TEST_F(RenderWidgetHostViewMacTest,
                       GetFirstRectForCharacterRangeUncached) {
  GURL url("data:text/html,Hello");
  EXPECT_TRUE(NavigateToURL(shell(), url));

  auto* web_contents_impl =
      static_cast<WebContentsImpl*>(shell()->web_contents());
  auto* root = web_contents_impl->GetPrimaryFrameTree().root();
  web_contents_impl->GetPrimaryFrameTree().SetFocusedFrame(
      root, root->current_frame_host()->GetSiteInstance()->group());

  RenderWidgetHostView* rwhv =
      shell()->web_contents()->GetPrimaryMainFrame()->GetView();
  RenderWidgetHostViewMac* rwhv_mac =
      static_cast<RenderWidgetHostViewMac*>(rwhv);

  NSRect rect = [rwhv_mac->GetInProcessNSView()
      firstRectForCharacterRange:NSMakeRange(2, 1)
                     actualRange:nullptr];
  EXPECT_GT(NSMinX(rect), 0);
  EXPECT_GT(NSWidth(rect), 0);
  EXPECT_GT(NSHeight(rect), 0);
}

IN_PROC_BROWSER_TEST_F(RenderWidgetHostViewMacTest, UpdateInputFlags) {
  class InputMethodObserver {};

  GURL url("data:text/html,<!doctype html><textarea id=ta></textarea>");
  EXPECT_TRUE(NavigateToURL(shell(), url));

  RenderWidgetHostView* rwhv =
      shell()->web_contents()->GetPrimaryMainFrame()->GetView();
  RenderWidgetHostViewMac* rwhv_mac =
      static_cast<RenderWidgetHostViewMac*>(rwhv);
  RenderWidgetHostViewCocoa* rwhv_cocoa = rwhv_mac->GetInProcessNSView();
  TextInputFlagChangeWaiter* flag_change_waiter =
      [[TextInputFlagChangeWaiter alloc]
          initWithRenderWidgetHostViewCocoa:rwhv_cocoa];

  EXPECT_TRUE(ExecJs(shell(), "ta.focus();"));
  [flag_change_waiter wait];
  EXPECT_FALSE(rwhv_cocoa.textInputFlags &
               blink::kWebTextInputFlagAutocorrectOff);

  EXPECT_TRUE(ExecJs(
      shell(),
      "ta.setAttribute('autocorrect', 'off'); console.log(ta.outerHTML);"));
  [flag_change_waiter wait];
  EXPECT_TRUE(rwhv_cocoa.textInputFlags &
              blink::kWebTextInputFlagAutocorrectOff);
}

// TODO(crbug.com/421820726): Enable the test.
#if BUILDFLAG(IS_MAC)
#define MAYBE_InputTextPreventedSyncsCursorLocation \
  DISABLED_InputTextPreventedSyncsCursorLocation
#else
#define MAYBE_InputTextPreventedSyncsCursorLocation \
  InputTextPreventedSyncsCursorLocation
#endif
IN_PROC_BROWSER_TEST_F(RenderWidgetHostViewMacTest,
                       MAYBE_InputTextPreventedSyncsCursorLocation) {
  class InputMethodObserver {};

  GURL url("data:text/html,<!doctype html><textarea id=ta></textarea>");
  EXPECT_TRUE(NavigateToURL(shell(), url));

  RenderWidgetHostView* rwhv =
      shell()->web_contents()->GetPrimaryMainFrame()->GetView();
  RenderWidgetHostViewMac* rwhv_mac =
      static_cast<RenderWidgetHostViewMac*>(rwhv);
  RenderWidgetHostViewCocoa* rwhv_cocoa = rwhv_mac->GetInProcessNSView();

  EXPECT_TRUE(ExecJs(
      shell(),
      "ta.addEventListener('keypress', (evt) => {evt.preventDefault();}); "
      "ta.focus();"));

  // Before typing anything, we're at position 0.
  EXPECT_EQ(0lu, [rwhv_cocoa selectedRange].location);

  TextSelectionWaiter waiter(rwhv_mac);
  NSEvent* key_a = cocoa_test_event_utils::KeyEventWithKeyCode(
      'a', 'a', NSEventTypeKeyDown, 0);
  [rwhv_cocoa keyEvent:key_a];

  // After typing 'a', the browser process assumes that the text was entered and
  // we are at position 1.
  EXPECT_EQ(1lu, [rwhv_cocoa selectedRange].location);

  // Wait for the renderer to sync the selection to the browser.
  waiter.Wait();

  // The synced selection updates the selected position back to 0.
  EXPECT_EQ(0lu, [rwhv_cocoa selectedRange].location);
}

// Tests that accessibility role requests sent to the web contents enable
// basic (native + web contents) accessibility support.
IN_PROC_BROWSER_TEST_F(RenderWidgetHostViewMacTest,
                       RespondToAccessibilityRoleRequestsOnWebContent) {
  if (base::mac::MacOSVersion() < 14'00'00) {
    GTEST_SKIP();
  }

  // Load some content.
  GURL url("data:text/html,<!doctype html><textarea id=ta></textarea>");
  EXPECT_TRUE(NavigateToURL(shell(), url));

  content::BrowserAccessibilityState* accessibility_state =
      content::BrowserAccessibilityState::GetInstance();

  // No accessibility support enabled at this time.
  EXPECT_EQ(accessibility_state->GetAccessibilityMode(), ui::AXMode());

  // Enable platform activation since that is what is begin tested here.
  BrowserAccessibilityState::GetInstance()->SetActivationFromPlatformEnabled(
      /*enabled=*/true);

  // An AT descending the AX tree calls -accessibilityRole on the nodes as it
  // goes. Simulate an AT calling -accessibilityRole on the web contents.
  RenderWidgetHostView* rwhv =
      shell()->web_contents()->GetPrimaryMainFrame()->GetView();
  RenderWidgetHostViewMac* rwhv_mac =
      static_cast<RenderWidgetHostViewMac*>(rwhv);
  RenderWidgetHostViewCocoa* rwhv_cocoa = rwhv_mac->GetInProcessNSView();

  [rwhv_cocoa accessibilityRole];

  // Calling -accessibilityRole on the RenderWidgetHostViewCocoa should have
  // activated basic accessibility support.
  EXPECT_EQ(accessibility_state->GetAccessibilityMode(), ui::kAXModeBasic);
}

// Tests that text replacement is not accepted during intermediate selection
// adjustment on backward deletion in EditContext.
IN_PROC_BROWSER_TEST_F(RenderWidgetHostViewMacTest,
                       EditContextTextReplacementOnBackSpace) {
  // Create a simple HTML page with EditContext.
  GURL url("data:text/html,<div id=editor></div>"
           "<script>"
           "const editor = document.getElementById('editor');"
           "editor.editContext = new EditContext();"
           "</script>");
  EXPECT_TRUE(NavigateToURL(shell(), url));

  RenderWidgetHostView* rwhv =
      shell()->web_contents()->GetPrimaryMainFrame()->GetView();
  RenderWidgetHostViewMac* rwhv_mac =
      static_cast<RenderWidgetHostViewMac*>(rwhv);
  RenderWidgetHostViewCocoa* rwhv_cocoa = rwhv_mac->GetInProcessNSView();

  // Set up fake spell checker to provide text replacement.
  FakeSpellChecker* fakeSpellChecker = [[FakeSpellChecker alloc] init];
  rwhv_cocoa.spellCheckerForTesting =
      static_cast<NSSpellChecker*>(fakeSpellChecker);

  EXPECT_TRUE(ExecJs(shell(), "editor.focus()"));

  // Ensure the input router is active to handle key events.
  static_cast<RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost())
      ->input_router()
      ->MakeActive();

  // Type "omw" character by character.
  NSString* testWord = @"omw";
  for (NSUInteger i = 0; i < [testWord length]; i++) {
    unichar c = [testWord characterAtIndex:i];
    NSEvent* keyDownEvent = cocoa_test_event_utils::KeyEventWithKeyCode(
        c, c, NSEventTypeKeyDown, 0);
    [rwhv_cocoa keyEvent:keyDownEvent];

    NSEvent* keyUpEvent =
        cocoa_test_event_utils::KeyEventWithKeyCode(c, c, NSEventTypeKeyUp, 0);
    [rwhv_cocoa keyEvent:keyUpEvent];

    [fakeSpellChecker waitForCheckString];
  }

  std::string current_value =
      EvalJs(shell(), "editor.editContext.text").ExtractString();
  EXPECT_EQ("omw", current_value);

  // For active text replacement suggestion, the completion handler should be
  // set.
  EXPECT_TRUE(fakeSpellChecker.correctionCompletionHandler != nil)
      << "showCorrectionIndicatorOfType should be called";

  TextSelectionWaiter selection_waiter(rwhv_mac);
  NSEvent* backspaceDownEvent = cocoa_test_event_utils::KeyEventWithKeyCode(
      kVK_Delete, '\b', NSEventTypeKeyDown, 0);
  [rwhv_cocoa keyEvent:backspaceDownEvent];

  NSEvent* backspaceUpEvent = cocoa_test_event_utils::KeyEventWithKeyCode(
      kVK_Delete, '\b', NSEventTypeKeyUp, 0);
  [rwhv_cocoa keyEvent:backspaceUpEvent];
  selection_waiter.Wait();

  std::string final_value =
      EvalJs(shell(), "editor.editContext.text").ExtractString();

  EXPECT_EQ("om", final_value)
      << "Text replacement should not be accepted on backward deletion.";
}

// Tests that text replacement is not accepted during DOM update when there is
// an active EditContext.
IN_PROC_BROWSER_TEST_F(RenderWidgetHostViewMacTest,
                       EditContextTextReplacementOnDOMSelectionUpdate) {
  // Create a simple HTML page with EditContext.
  GURL url("data:text/html,<div id=editor></div>"
           "<script>"
           "const editor = document.getElementById('editor');"
           "editor.editContext = new EditContext();"
           "editor.editContext.addEventListener('textupdate', (event) => {"
           "if(editor.editContext.text == 'omw') {"
           "editor.innerText = 'omw';"
           "document.getSelection().collapse(editor.firstChild, "
           "editor.innerText.length);"
           "}"
           "});"
           "</script>");
  EXPECT_TRUE(NavigateToURL(shell(), url));

  RenderWidgetHostView* rwhv =
      shell()->web_contents()->GetPrimaryMainFrame()->GetView();
  RenderWidgetHostViewMac* rwhv_mac =
      static_cast<RenderWidgetHostViewMac*>(rwhv);
  RenderWidgetHostViewCocoa* rwhv_cocoa = rwhv_mac->GetInProcessNSView();

  // Set up fake spell checker to provide text replacement.
  FakeSpellChecker* fakeSpellChecker = [[FakeSpellChecker alloc] init];
  rwhv_cocoa.spellCheckerForTesting =
      static_cast<NSSpellChecker*>(fakeSpellChecker);

  EXPECT_TRUE(ExecJs(shell(), "editor.focus()"));

  // Ensure the input router is active to handle key events.
  static_cast<RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost())
      ->input_router()
      ->MakeActive();

  // Type "omw" character by character.
  NSString* testWord = @"omw";
  for (NSUInteger i = 0; i < [testWord length]; i++) {
    unichar c = [testWord characterAtIndex:i];
    NSEvent* keyDownEvent = cocoa_test_event_utils::KeyEventWithKeyCode(
        c, c, NSEventTypeKeyDown, 0);
    [rwhv_cocoa keyEvent:keyDownEvent];

    NSEvent* keyUpEvent =
        cocoa_test_event_utils::KeyEventWithKeyCode(c, c, NSEventTypeKeyUp, 0);
    [rwhv_cocoa keyEvent:keyUpEvent];

    [fakeSpellChecker waitForCheckString];
  }

  std::string text = EvalJs(shell(), "editor.editContext.text").ExtractString();
  EXPECT_EQ("omw", text);

  // For active text replacement suggestion, the completion handler should be
  // set.
  EXPECT_TRUE(fakeSpellChecker.correctionCompletionHandler != nil)
      << "showCorrectionIndicatorOfType should be called";

  // Wait for any pending DOM update or selection sync to complete between
  // browser and renderer process.
  std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>();
  base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE, run_loop->QuitClosure(), base::Milliseconds(1000));
  run_loop->Run();

  // Verify that the text is set in editor and DOM selection is updated.
  text = EvalJs(shell(), "editor.editContext.text").ExtractString();
  EXPECT_EQ("omw", text)
      << "Text replacement should not be accepted on DOM selection update.";
  EXPECT_EQ(
      3, EvalJs(shell(), "document.getSelection().anchorOffset").ExtractInt());
  EXPECT_EQ(
      3, EvalJs(shell(), "document.getSelection().focusOffset").ExtractInt());

  // Wait for selection sync between browser and renderer process.
  // Selection should be synced twice: [1] for inserting ' ' and [2] when text
  // replacement is accepted.
  TextSelectionWaiter selection_waiter(rwhv_mac, 2);
  // Type space to trigger text replacement.
  NSEvent* spaceDownEvent = cocoa_test_event_utils::KeyEventWithKeyCode(
      ' ', ' ', NSEventTypeKeyDown, 0);
  [rwhv_cocoa keyEvent:spaceDownEvent];

  NSEvent* spaceUpEvent = cocoa_test_event_utils::KeyEventWithKeyCode(
      ' ', ' ', NSEventTypeKeyUp, 0);
  [rwhv_cocoa keyEvent:spaceUpEvent];
  selection_waiter.Wait();

  text = EvalJs(shell(), "editor.editContext.text").ExtractString();
  EXPECT_EQ("On my way ", text)
      << "Text replacement should be accepted on space.";
}

}  // namespace content