summaryrefslogtreecommitdiff
path: root/chromium/content/browser/system_connector_impl.cc
blob: ad1679f741b930560e41dcd57da22605d5899feb (plain)
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
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/system_connector_impl.h"

#include "base/check_op.h"
#include "base/no_destructor.h"
#include "base/threading/sequence_local_storage_slot.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"

namespace content {

namespace {

base::SequenceLocalStorageSlot<service_manager::Connector>&
GetConnectorStorage() {
  static base::NoDestructor<
      base::SequenceLocalStorageSlot<service_manager::Connector>>
      storage;
  return *storage;
}

void BindReceiverOnMainThread(
    mojo::PendingReceiver<service_manager::mojom::Connector> receiver) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  auto* main_thread_connector = GetSystemConnector();
  DCHECK(main_thread_connector)
      << "GetSystemConnector() called on background thread with no system "
      << "Connector set on the main thread. If this is a unit test "
      << "environment, consider calling SetSystemConnectorForTesting in test "
         "setup.";
  main_thread_connector->BindConnectorReceiver(std::move(receiver));
}

}  // namespace

service_manager::Connector* GetSystemConnector() {
  auto& storage = GetConnectorStorage();
  if (!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
      BrowserThread::CurrentlyOn(BrowserThread::UI)) {
    return storage.GetValuePointer();
  }

  if (!storage) {
    mojo::PendingRemote<service_manager::mojom::Connector> remote;
    GetUIThreadTaskRunner({})->PostTask(
        FROM_HERE, base::BindOnce(&BindReceiverOnMainThread,
                                  remote.InitWithNewPipeAndPassReceiver()));
    storage.emplace(std::move(remote));
  }

  return storage.GetValuePointer();
}

void SetSystemConnector(std::unique_ptr<service_manager::Connector> connector) {
  if (!connector) {
    GetConnectorStorage().reset();
    return;
  }
  mojo::PendingRemote<service_manager::mojom::Connector> remote;
  connector->BindConnectorReceiver(remote.InitWithNewPipeAndPassReceiver());
  GetConnectorStorage().emplace(std::move(remote));
}

void SetSystemConnectorForTesting(
    std::unique_ptr<service_manager::Connector> connector) {
  SetSystemConnector(std::move(connector));
}

}  // namespace content