55fd41f04df08cbce22b6d548767f07328bfd203
[platform/framework/web/crosswalk.git] / src / mojo / shell / service_manager.cc
1 // Copyright 2013 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 "mojo/shell/service_manager.h"
6
7 #include "base/logging.h"
8 #include "mojo/public/bindings/lib/remote_ptr.h"
9 #include "mojom/shell.h"
10
11 namespace mojo {
12 namespace shell {
13
14 class ServiceManager::Service : public Shell {
15  public:
16   Service(ServiceManager* manager, const GURL& url)
17       : manager_(manager),
18         url_(url) {
19     MessagePipe pipe;
20     shell_client_.reset(pipe.handle0.Pass(), this);
21     manager_->GetLoaderForURL(url)->Load(url, pipe.handle1.Pass());
22   }
23   virtual ~Service() {}
24
25   void ConnectToClient(ScopedMessagePipeHandle handle) {
26     if (handle.is_valid())
27       shell_client_->AcceptConnection(handle.Pass());
28   }
29
30   virtual void Connect(const String& url,
31                        ScopedMessagePipeHandle client_pipe) MOJO_OVERRIDE {
32     manager_->Connect(GURL(url.To<std::string>()), client_pipe.Pass());
33   }
34
35  private:
36   ServiceManager* manager_;
37   GURL url_;
38   RemotePtr<ShellClient> shell_client_;
39   DISALLOW_COPY_AND_ASSIGN(Service);
40 };
41
42 ServiceManager::Loader::Loader() {}
43 ServiceManager::Loader::~Loader() {}
44
45 ServiceManager::ServiceManager() : default_loader_(NULL) {
46 }
47
48 ServiceManager::~ServiceManager() {
49   for (ServiceMap::iterator it = url_to_service_.begin();
50        it != url_to_service_.end(); ++it) {
51     delete it->second;
52   }
53   url_to_service_.clear();
54 }
55
56 void ServiceManager::SetLoaderForURL(Loader* loader, const GURL& gurl) {
57   DCHECK(url_to_loader_.find(gurl) == url_to_loader_.end());
58   url_to_loader_[gurl] = loader;
59 }
60
61 ServiceManager::Loader* ServiceManager::GetLoaderForURL(const GURL& gurl) {
62   LoaderMap::const_iterator it = url_to_loader_.find(gurl);
63   if (it != url_to_loader_.end())
64     return it->second;
65   DCHECK(default_loader_);
66   return default_loader_;
67 }
68
69 void ServiceManager::Connect(const GURL& url,
70                              ScopedMessagePipeHandle client_handle) {
71   ServiceMap::const_iterator service_it = url_to_service_.find(url);
72   Service* service;
73   if (service_it != url_to_service_.end()) {
74     service = service_it->second;
75   } else {
76     service = new Service(this, url);
77     url_to_service_[url] = service;
78   }
79   service->ConnectToClient(client_handle.Pass());
80 }
81
82 }  // namespace shell
83 }  // namespace mojo