File: spellcheck_per_process_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 (409 lines) | stat: -rw-r--r-- 14,316 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
// 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 <utility>
#include <vector>

// spellcheck_per_process_browsertest.cc

#include "base/feature_list.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/site_isolation/chrome_site_per_process_test.h"
#include "chrome/browser/spellchecker/spell_check_host_chrome_impl.h"
#include "chrome/browser/spellchecker/spellcheck_factory.h"
#include "chrome/browser/spellchecker/spellcheck_service.h"
#include "chrome/browser/ui/browser.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/prefs/pref_service.h"
#include "components/spellcheck/browser/pref_names.h"
#include "components/spellcheck/common/spellcheck.mojom.h"
#include "components/spellcheck/common/spellcheck_features.h"
#include "components/spellcheck/spellcheck_buildflags.h"
#include "components/user_prefs/user_prefs.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "services/service_manager/public/cpp/interface_provider.h"

#if BUILDFLAG(HAS_SPELLCHECK_PANEL)
#include "chrome/browser/spellchecker/test/spellcheck_panel_browsertest_helper.h"
#include "components/spellcheck/common/spellcheck_panel.mojom.h"
#include "mojo/public/cpp/bindings/remote.h"
#endif  // BUILDFLAG(HAS_SPELLCHECK_PANEL)

// Class to sniff incoming spellcheck Mojo SpellCheckHost messages.
class MockSpellCheckHost : spellcheck::mojom::SpellCheckHost {
 public:
  explicit MockSpellCheckHost(content::RenderProcessHost* process_host)
      : process_host_(process_host) {}

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

  ~MockSpellCheckHost() override = default;

  content::RenderProcessHost* process_host() const { return process_host_; }

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

  bool HasReceivedText() const { return text_received_; }

  void Wait() {
    if (text_received_)
      return;

    base::RunLoop run_loop;
    quit_ = run_loop.QuitClosure();
    run_loop.Run();
  }

  void WaitUntilTimeout() {
    if (text_received_)
      return;

    auto ui_task_runner = content::GetUIThreadTaskRunner({});
    ui_task_runner->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(&MockSpellCheckHost::Timeout, base::Unretained(this)),
        base::Seconds(1));

    base::RunLoop run_loop;
    quit_ = run_loop.QuitClosure();
    run_loop.Run();
  }

  void SpellCheckHostReceiver(
      mojo::PendingReceiver<spellcheck::mojom::SpellCheckHost> receiver) {
    EXPECT_FALSE(receiver_.is_bound());
    receiver_.Bind(std::move(receiver));
  }

 private:
  void TextReceived(const std::u16string& text) {
    text_received_ = true;
    text_ = text;
    receiver_.reset();
    if (quit_)
      std::move(quit_).Run();
  }

  void Timeout() {
    if (quit_)
      std::move(quit_).Run();
  }

  // spellcheck::mojom::SpellCheckHost:
  void NotifyChecked(const std::u16string& word, bool misspelled) override {}

#if BUILDFLAG(USE_RENDERER_SPELLCHECKER)
  void CallSpellingService(const std::u16string& text,
                           CallSpellingServiceCallback callback) override {
    DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
    std::move(callback).Run(true, std::vector<SpellCheckResult>());
    TextReceived(text);
  }
#endif

#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
  void RequestTextCheck(const std::u16string& text,
                        RequestTextCheckCallback callback) override {
    DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
    std::move(callback).Run(std::vector<SpellCheckResult>());
    TextReceived(text);
  }

  void CheckSpelling(const std::u16string& word,
                     CheckSpellingCallback) override {}
  void FillSuggestionList(const std::u16string& word,
                          FillSuggestionListCallback) override {}

#if BUILDFLAG(IS_WIN)
  void InitializeDictionaries(
      InitializeDictionariesCallback callback) override {
    if (base::FeatureList::IsEnabled(
            spellcheck::kWinDelaySpellcheckServiceInit)) {
      SpellcheckService* spellcheck = SpellcheckServiceFactory::GetForContext(
          process_host()->GetBrowserContext());

      if (!spellcheck) {  // Teardown.
        std::move(callback).Run(/*dictionaries=*/{}, /*custom_words=*/{},
                                /*enable=*/false);
        return;
      }

      dictionaries_loaded_callback_ = std::move(callback);

      spellcheck->InitializeDictionaries(
          base::BindOnce(&MockSpellCheckHost::OnDictionariesInitialized,
                         base::Unretained(this)));
      return;
    }

    NOTREACHED();
  }

  void OnDictionariesInitialized() {
    if (dictionaries_loaded_callback_) {
      std::vector<spellcheck::mojom::SpellCheckBDictLanguagePtr> dictionaries;
      dictionaries.push_back(spellcheck::mojom::SpellCheckBDictLanguage::New(
          base::File(), "en-US"));

      std::move(dictionaries_loaded_callback_)
          .Run(std::move(dictionaries), {}, true);
    }
  }

  // Callback passed as argument to InitializeDictionaries, and invoked when
  // the dictionaries are loaded for the first time.
  InitializeDictionariesCallback dictionaries_loaded_callback_;
#endif  // BUILDFLAG(IS_WIN)
#endif  // BUILDFLAG(USE_BROWSER_SPELLCHECKER)

#if BUILDFLAG(IS_ANDROID)
  // spellcheck::mojom::SpellCheckHost:
  void DisconnectSessionBridge() override {}
#endif

  raw_ptr<content::RenderProcessHost> process_host_;
  bool text_received_ = false;
  std::u16string text_;
  mojo::Receiver<spellcheck::mojom::SpellCheckHost> receiver_{this};
  base::OnceClosure quit_;
};

class SpellCheckBrowserTestHelper {
 public:
  SpellCheckBrowserTestHelper() {
    SpellCheckHostChromeImpl::OverrideBinderForTesting(
        base::BindRepeating(&SpellCheckBrowserTestHelper::BindSpellCheckHost,
                            base::Unretained(this)));
  }

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

  ~SpellCheckBrowserTestHelper() {
    SpellCheckHostChromeImpl::OverrideBinderForTesting(base::NullCallback());
  }

  // Retrieves the registered MockSpellCheckHost for the given
  // RenderProcessHost. It will return nullptr if the RenderProcessHost was
  // initialized while a different instance of ContentBrowserClient was in
  // action.
  MockSpellCheckHost* GetSpellCheckHostForProcess(
      content::RenderProcessHost* process_host) const {
    for (auto& spell_check_host : spell_check_hosts_) {
      if (spell_check_host->process_host() == process_host)
        return spell_check_host.get();
    }
    return nullptr;
  }

  void RunUntilBind() {
    if (!spell_check_hosts_.empty())
      return;

    base::RunLoop run_loop;
    quit_on_bind_closure_ = run_loop.QuitClosure();
    run_loop.Run();
  }

  void RunUntilBindOrTimeout() {
    if (!spell_check_hosts_.empty())
      return;

    auto ui_task_runner = content::GetUIThreadTaskRunner({});
    ui_task_runner->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(&SpellCheckBrowserTestHelper::Timeout,
                       base::Unretained(this)),
        base::Seconds(1));

    base::RunLoop run_loop;
    quit_on_bind_closure_ = run_loop.QuitClosure();
    run_loop.Run();
  }

 private:
  void BindSpellCheckHost(
      int render_process_id,
      mojo::PendingReceiver<spellcheck::mojom::SpellCheckHost> receiver) {
    content::RenderProcessHost* host =
        content::RenderProcessHost::FromID(render_process_id);
    auto spell_check_host = std::make_unique<MockSpellCheckHost>(host);
    spell_check_host->SpellCheckHostReceiver(std::move(receiver));
    spell_check_hosts_.push_back(std::move(spell_check_host));
    if (quit_on_bind_closure_)
      std::move(quit_on_bind_closure_).Run();
  }

  void Timeout() {
    if (quit_on_bind_closure_)
      std::move(quit_on_bind_closure_).Run();
  }

  base::OnceClosure quit_on_bind_closure_;
  std::vector<std::unique_ptr<MockSpellCheckHost>> spell_check_hosts_;
};

class ChromeSitePerProcessSpellCheckTest : public ChromeSitePerProcessTest {
 public:
  ChromeSitePerProcessSpellCheckTest() = default;

  void SetUp() override {
#if BUILDFLAG(IS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
    // When delayed initialization of the spellcheck service is enabled by
    // default, want to maintain test coverage for the older code path that
    // initializes spellcheck on browser startup.
    feature_list_.InitAndDisableFeature(
        spellcheck::kWinDelaySpellcheckServiceInit);
#endif  // BUILDFLAG(IS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)

    ChromeSitePerProcessTest::SetUp();
  }

 protected:
  // Tests that spelling in out-of-process subframes is checked.
  // See crbug.com/638361 for details.
  void RunOOPIFSpellCheckTest() {
    SpellCheckBrowserTestHelper spell_check_helper;

    GURL main_url(embedded_test_server()->GetURL(
        "a.com", "/page_with_contenteditable_in_cross_site_subframe.html"));
    ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), main_url));
    spell_check_helper.RunUntilBind();

    content::WebContents* web_contents =
        browser()->tab_strip_model()->GetActiveWebContents();
    content::RenderFrameHost* cross_site_subframe =
        ChildFrameAt(web_contents->GetPrimaryMainFrame(), 0);

    MockSpellCheckHost* spell_check_host =
        spell_check_helper.GetSpellCheckHostForProcess(
            cross_site_subframe->GetProcess());
    spell_check_host->Wait();

    EXPECT_EQ(u"zz.", spell_check_host->text());
  }

  // Tests that after disabling spellchecking, spelling in new out-of-process
  // subframes is not checked. See crbug.com/789273 for details.
  // https://crbug.com/944428
  void RunOOPIFDisabledSpellCheckTest() {
    SpellCheckBrowserTestHelper spell_check_helper;

    content::BrowserContext* browser_context =
        static_cast<content::BrowserContext*>(browser()->profile());

    // Initiate a SpellcheckService
    SpellcheckServiceFactory::GetForContext(browser_context);

    // Disable spellcheck
    PrefService* prefs = user_prefs::UserPrefs::Get(browser_context);
    prefs->SetBoolean(spellcheck::prefs::kSpellCheckEnable, false);
    base::RunLoop().RunUntilIdle();

    GURL main_url(embedded_test_server()->GetURL(
        "a.com", "/page_with_contenteditable_in_cross_site_subframe.html"));
    ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), main_url));
    spell_check_helper.RunUntilBindOrTimeout();

    content::WebContents* web_contents =
        browser()->tab_strip_model()->GetActiveWebContents();
    content::RenderFrameHost* cross_site_subframe =
        ChildFrameAt(web_contents->GetPrimaryMainFrame(), 0);

    MockSpellCheckHost* spell_check_host =
        spell_check_helper.GetSpellCheckHostForProcess(
            cross_site_subframe->GetProcess());

    // The renderer makes no SpellCheckHostReceiver at all, in which case no
    // SpellCheckHost is bound and no spellchecking will be done.
    EXPECT_FALSE(spell_check_host);

    prefs->SetBoolean(spellcheck::prefs::kSpellCheckEnable, true);
  }

  base::test::ScopedFeatureList feature_list_;
};

IN_PROC_BROWSER_TEST_F(ChromeSitePerProcessSpellCheckTest,
                       OOPIFSpellCheckTest) {
  RunOOPIFSpellCheckTest();
}

IN_PROC_BROWSER_TEST_F(ChromeSitePerProcessSpellCheckTest,
                       OOPIFDisabledSpellCheckTest) {
  RunOOPIFDisabledSpellCheckTest();
}

#if BUILDFLAG(HAS_SPELLCHECK_PANEL)
// Tests that the OSX spell check panel can be opened from an out-of-process
// subframe, crbug.com/712395
IN_PROC_BROWSER_TEST_F(ChromeSitePerProcessSpellCheckTest,
                       OOPIFSpellCheckPanelTest) {
  spellcheck::SpellCheckPanelBrowserTestHelper test_helper;

  GURL main_url(embedded_test_server()->GetURL(
      "a.com", "/page_with_contenteditable_in_cross_site_subframe.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), main_url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  content::RenderFrameHost* cross_site_subframe =
      ChildFrameAt(web_contents->GetPrimaryMainFrame(), 0);

  EXPECT_TRUE(cross_site_subframe->IsCrossProcessSubframe());

  mojo::Remote<spellcheck::mojom::SpellCheckPanel> spell_check_panel_client;
  cross_site_subframe->GetRemoteInterfaces()->GetInterface(
      spell_check_panel_client.BindNewPipeAndPassReceiver());
  spell_check_panel_client->ToggleSpellPanel(false);
  test_helper.RunUntilBind();

  spellcheck::SpellCheckMockPanelHost* host =
      test_helper.GetSpellCheckMockPanelHostForProcess(
          cross_site_subframe->GetProcess());
  EXPECT_TRUE(host->SpellingPanelVisible());
}
#endif  // BUILDFLAG(HAS_SPELLCHECK_PANEL)

#if BUILDFLAG(IS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
class ChromeSitePerProcessSpellCheckTestDelayInit
    : public ChromeSitePerProcessSpellCheckTest {
 public:
  ChromeSitePerProcessSpellCheckTestDelayInit() = default;

  void SetUp() override {
    // Don't initialize the SpellcheckService on browser launch.
    feature_list_.InitAndEnableFeature(
        spellcheck::kWinDelaySpellcheckServiceInit);

    ChromeSitePerProcessTest::SetUp();
  }
};

IN_PROC_BROWSER_TEST_F(ChromeSitePerProcessSpellCheckTestDelayInit,
                       OOPIFSpellCheckTest) {
  RunOOPIFSpellCheckTest();
}

IN_PROC_BROWSER_TEST_F(ChromeSitePerProcessSpellCheckTestDelayInit,
                       OOPIFDisabledSpellCheckTest) {
  RunOOPIFDisabledSpellCheckTest();
}
#endif  // BUILDFLAG(IS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)