service_registry_impl.cc revision 116680a4aac90f2aa7413d9095a592090648e557
1// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "content/common/mojo/service_registry_impl.h"
6
7#include "mojo/common/common_type_converters.h"
8
9namespace content {
10
11ServiceRegistryImpl::ServiceRegistryImpl() : bound_(false) {
12}
13
14ServiceRegistryImpl::ServiceRegistryImpl(mojo::ScopedMessagePipeHandle handle)
15    : bound_(false) {
16  BindRemoteServiceProvider(handle.Pass());
17}
18
19ServiceRegistryImpl::~ServiceRegistryImpl() {
20  while (!pending_connects_.empty()) {
21    mojo::CloseRaw(pending_connects_.front().second);
22    pending_connects_.pop();
23  }
24}
25
26void ServiceRegistryImpl::BindRemoteServiceProvider(
27    mojo::ScopedMessagePipeHandle handle) {
28  DCHECK(!bound_);
29  bound_ = true;
30  mojo::BindToPipe(this, handle.Pass());
31  while (!pending_connects_.empty()) {
32    client()->ConnectToService(
33        mojo::String::From(pending_connects_.front().first),
34        mojo::ScopedMessagePipeHandle(pending_connects_.front().second));
35    pending_connects_.pop();
36  }
37}
38
39void ServiceRegistryImpl::OnConnectionError() {
40  // TODO(sammc): Support reporting this to our owner.
41}
42
43void ServiceRegistryImpl::AddService(
44    const std::string& service_name,
45    const base::Callback<void(mojo::ScopedMessagePipeHandle)> service_factory) {
46  bool inserted = service_factories_.insert(
47      std::make_pair(service_name, service_factory)).second;
48  DCHECK(inserted);
49}
50
51void ServiceRegistryImpl::RemoveService(const std::string& service_name) {
52  service_factories_.erase(service_name);
53}
54
55void ServiceRegistryImpl::ConnectToRemoteService(
56    const base::StringPiece& service_name,
57    mojo::ScopedMessagePipeHandle handle) {
58  if (!bound_) {
59    pending_connects_.push(
60        std::make_pair(service_name.as_string(), handle.release()));
61    return;
62  }
63  client()->ConnectToService(mojo::String::From(service_name), handle.Pass());
64}
65
66void ServiceRegistryImpl::ConnectToService(
67    const mojo::String& name,
68    mojo::ScopedMessagePipeHandle client_handle) {
69  std::map<std::string,
70           base::Callback<void(mojo::ScopedMessagePipeHandle)> >::iterator it =
71      service_factories_.find(name);
72  if (it == service_factories_.end())
73    return;
74
75  it->second.Run(client_handle.Pass());
76}
77
78}  // namespace content
79