Remove obsolete entries from .gitignore.
[chromium-blink-merge.git] / mojo / runner / context.cc
blob048de9bf4be3c86b2d37a8ac3ee933920d2af0e8
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.
5 #include "mojo/runner/context.h"
7 #include <vector>
9 #include "base/bind.h"
10 #include "base/command_line.h"
11 #include "base/files/file_path.h"
12 #include "base/lazy_instance.h"
13 #include "base/macros.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/path_service.h"
16 #include "base/process/process_info.h"
17 #include "base/run_loop.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_split.h"
20 #include "base/strings/string_util.h"
21 #include "base/trace_event/trace_event.h"
22 #include "build/build_config.h"
23 #include "components/devtools_service/public/cpp/switches.h"
24 #include "components/devtools_service/public/interfaces/devtools_service.mojom.h"
25 #include "mojo/application/public/cpp/application_connection.h"
26 #include "mojo/application/public/cpp/application_delegate.h"
27 #include "mojo/application/public/cpp/application_impl.h"
28 #include "mojo/common/trace_controller_impl.h"
29 #include "mojo/common/tracing_impl.h"
30 #include "mojo/edk/embedder/embedder.h"
31 #include "mojo/edk/embedder/simple_platform_support.h"
32 #include "mojo/package_manager/package_manager_impl.h"
33 #include "mojo/runner/in_process_native_runner.h"
34 #include "mojo/runner/out_of_process_native_runner.h"
35 #include "mojo/runner/switches.h"
36 #include "mojo/services/tracing/public/cpp/switches.h"
37 #include "mojo/services/tracing/public/interfaces/tracing.mojom.h"
38 #include "mojo/shell/application_loader.h"
39 #include "mojo/shell/connect_to_application_params.h"
40 #include "mojo/shell/query_util.h"
41 #include "mojo/shell/switches.h"
42 #include "mojo/util/filename_util.h"
43 #include "url/gurl.h"
45 namespace mojo {
46 namespace runner {
47 namespace {
49 // Used to ensure we only init once.
50 class Setup {
51 public:
52 Setup() {
53 embedder::Init(make_scoped_ptr(new embedder::SimplePlatformSupport()));
56 ~Setup() {}
58 private:
59 DISALLOW_COPY_AND_ASSIGN(Setup);
62 void InitContentHandlers(package_manager::PackageManagerImpl* manager,
63 const base::CommandLine& command_line) {
64 // Default content handlers.
65 manager->RegisterContentHandler("application/pdf", GURL("mojo:pdf_viewer"));
66 manager->RegisterContentHandler("image/png", GURL("mojo:png_viewer"));
67 manager->RegisterContentHandler("text/html", GURL("mojo:html_viewer"));
68 manager->RegisterContentHandler("text/plain", GURL("mojo:html_viewer"));
70 // Command-line-specified content handlers.
71 std::string handlers_spec =
72 command_line.GetSwitchValueASCII(switches::kContentHandlers);
73 if (handlers_spec.empty())
74 return;
76 #if defined(OS_ANDROID)
77 // TODO(eseidel): On Android we pass command line arguments is via the
78 // 'parameters' key on the intent, which we specify during 'am shell start'
79 // via --esa, however that expects comma-separated values and says:
80 // am shell --help:
81 // [--esa <EXTRA_KEY> <EXTRA_STRING_VALUE>[,<EXTRA_STRING_VALUE...]]
82 // (to embed a comma into a string escape it using "\,")
83 // Whatever takes 'parameters' and constructs a CommandLine is failing to
84 // un-escape the commas, we need to move this fix to that file.
85 base::ReplaceSubstringsAfterOffset(&handlers_spec, 0, "\\,", ",");
86 #endif
88 std::vector<std::string> parts = base::SplitString(
89 handlers_spec, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
90 if (parts.size() % 2 != 0) {
91 LOG(ERROR) << "Invalid value for switch " << switches::kContentHandlers
92 << ": must be a comma-separated list of mimetype/url pairs."
93 << handlers_spec;
94 return;
97 for (size_t i = 0; i < parts.size(); i += 2) {
98 GURL url(parts[i + 1]);
99 if (!url.is_valid()) {
100 LOG(ERROR) << "Invalid value for switch " << switches::kContentHandlers
101 << ": '" << parts[i + 1] << "' is not a valid URL.";
102 return;
104 // TODO(eseidel): We should also validate that the mimetype is valid
105 // net/base/mime_util.h could do this, but we don't want to depend on net.
106 manager->RegisterContentHandler(parts[i], url);
110 void InitDevToolsServiceIfNeeded(shell::ApplicationManager* manager,
111 const base::CommandLine& command_line) {
112 if (!command_line.HasSwitch(devtools_service::kRemoteDebuggingPort))
113 return;
115 std::string port_str =
116 command_line.GetSwitchValueASCII(devtools_service::kRemoteDebuggingPort);
117 unsigned port;
118 if (!base::StringToUint(port_str, &port) || port > 65535) {
119 LOG(ERROR) << "Invalid value for switch "
120 << devtools_service::kRemoteDebuggingPort << ": '" << port_str
121 << "' is not a valid port number.";
122 return;
125 ServiceProviderPtr devtools_service_provider;
126 scoped_ptr<shell::ConnectToApplicationParams> params(
127 new shell::ConnectToApplicationParams);
128 params->set_originator_identity(shell::Identity(GURL("mojo:shell")));
129 params->set_originator_filter(shell::GetPermissiveCapabilityFilter());
130 params->SetURLInfo(GURL("mojo:devtools_service"));
131 params->set_services(GetProxy(&devtools_service_provider));
132 params->set_filter(shell::GetPermissiveCapabilityFilter());
133 manager->ConnectToApplication(params.Pass());
135 devtools_service::DevToolsCoordinatorPtr devtools_coordinator;
136 devtools_service_provider->ConnectToService(
137 devtools_service::DevToolsCoordinator::Name_,
138 GetProxy(&devtools_coordinator).PassMessagePipe());
139 devtools_coordinator->Initialize(static_cast<uint16_t>(port));
142 class TracingServiceProvider : public ServiceProvider {
143 public:
144 explicit TracingServiceProvider(InterfaceRequest<ServiceProvider> request)
145 : binding_(this, request.Pass()) {}
146 ~TracingServiceProvider() override {}
148 void ConnectToService(const String& service_name,
149 ScopedMessagePipeHandle client_handle) override {
150 if (service_name == tracing::TraceController::Name_) {
151 new TraceControllerImpl(
152 MakeRequest<tracing::TraceController>(client_handle.Pass()));
156 private:
157 StrongBinding<ServiceProvider> binding_;
159 DISALLOW_COPY_AND_ASSIGN(TracingServiceProvider);
162 } // namespace
164 Context::Context(const base::FilePath& shell_file_root)
165 : shell_file_root_(shell_file_root),
166 package_manager_(nullptr),
167 main_entry_time_(base::Time::Now()) {}
169 Context::~Context() {
170 DCHECK(!base::MessageLoop::current());
173 // static
174 void Context::EnsureEmbedderIsInitialized() {
175 static base::LazyInstance<Setup>::Leaky setup = LAZY_INSTANCE_INITIALIZER;
176 setup.Get();
179 bool Context::Init() {
180 TRACE_EVENT0("mojo_shell", "Context::Init");
181 const base::CommandLine& command_line =
182 *base::CommandLine::ForCurrentProcess();
184 EnsureEmbedderIsInitialized();
185 task_runners_.reset(
186 new TaskRunners(base::MessageLoop::current()->task_runner()));
188 // TODO(vtl): This should be MASTER, not NONE.
189 embedder::InitIPCSupport(
190 embedder::ProcessType::NONE, task_runners_->shell_runner(), this,
191 task_runners_->io_runner(), embedder::ScopedPlatformHandle());
193 package_manager_ = new package_manager::PackageManagerImpl(shell_file_root_);
194 InitContentHandlers(package_manager_, command_line);
196 application_manager_.reset(
197 new shell::ApplicationManager(make_scoped_ptr(package_manager_)));
199 scoped_ptr<shell::NativeRunnerFactory> runner_factory;
200 if (command_line.HasSwitch(switches::kEnableMultiprocess))
201 runner_factory.reset(new OutOfProcessNativeRunnerFactory(this));
202 else
203 runner_factory.reset(new InProcessNativeRunnerFactory(this));
204 application_manager_->set_blocking_pool(task_runners_->blocking_pool());
205 application_manager_->set_native_runner_factory(runner_factory.Pass());
207 ServiceProviderPtr service_provider_ptr;
208 ServiceProviderPtr tracing_service_provider_ptr;
209 new TracingServiceProvider(GetProxy(&tracing_service_provider_ptr));
210 mojo::URLRequestPtr request(mojo::URLRequest::New());
211 request->url = mojo::String::From("mojo:tracing");
213 scoped_ptr<shell::ConnectToApplicationParams> params(
214 new shell::ConnectToApplicationParams);
215 params->SetURLInfo(request.Pass());
216 params->set_services(GetProxy(&service_provider_ptr));
217 params->set_exposed_services(tracing_service_provider_ptr.Pass());
218 params->set_filter(shell::GetPermissiveCapabilityFilter());
219 application_manager_->ConnectToApplication(params.Pass());
221 // Record the shell startup metrics used for performance testing.
222 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
223 tracing::kEnableStatsCollectionBindings)) {
224 tracing::StartupPerformanceDataCollectorPtr collector;
225 service_provider_ptr->ConnectToService(
226 tracing::StartupPerformanceDataCollector::Name_,
227 GetProxy(&collector).PassMessagePipe());
228 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
229 // CurrentProcessInfo::CreationTime is only defined on some platforms.
230 const base::Time creation_time = base::CurrentProcessInfo::CreationTime();
231 collector->SetShellProcessCreationTime(creation_time.ToInternalValue());
232 #endif
233 collector->SetShellMainEntryPointTime(main_entry_time_.ToInternalValue());
236 InitDevToolsServiceIfNeeded(application_manager_.get(), command_line);
238 return true;
241 void Context::Shutdown() {
242 // Actions triggered by ApplicationManager's destructor may require a current
243 // message loop, so we should destruct it explicitly now as ~Context() occurs
244 // post message loop shutdown.
245 application_manager_.reset();
247 TRACE_EVENT0("mojo_shell", "Context::Shutdown");
248 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
249 task_runners_->shell_runner());
250 embedder::ShutdownIPCSupport();
251 // We'll quit when we get OnShutdownComplete().
252 base::MessageLoop::current()->Run();
255 void Context::OnShutdownComplete() {
256 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
257 task_runners_->shell_runner());
258 base::MessageLoop::current()->Quit();
261 void Context::Run(const GURL& url) {
262 DCHECK(app_complete_callback_.is_null());
263 ServiceProviderPtr services;
264 ServiceProviderPtr exposed_services;
266 app_urls_.insert(url);
267 mojo::URLRequestPtr request(mojo::URLRequest::New());
268 request->url = mojo::String::From(url.spec());
270 scoped_ptr<shell::ConnectToApplicationParams> params(
271 new shell::ConnectToApplicationParams);
272 params->SetURLInfo(request.Pass());
273 params->set_services(GetProxy(&services));
274 params->set_exposed_services(exposed_services.Pass());
275 params->set_filter(shell::GetPermissiveCapabilityFilter());
276 params->set_on_application_end(
277 base::Bind(&Context::OnApplicationEnd, base::Unretained(this), url));
278 application_manager_->ConnectToApplication(params.Pass());
281 void Context::RunCommandLineApplication(const base::Closure& callback) {
282 DCHECK(app_urls_.empty());
283 DCHECK(app_complete_callback_.is_null());
284 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
285 base::CommandLine::StringVector args = command_line->GetArgs();
286 for (size_t i = 0; i < args.size(); ++i) {
287 GURL possible_app(args[i]);
288 if (possible_app.SchemeIs("mojo")) {
289 Run(possible_app);
290 app_complete_callback_ = callback;
291 break;
296 void Context::OnApplicationEnd(const GURL& url) {
297 if (app_urls_.find(url) != app_urls_.end()) {
298 app_urls_.erase(url);
299 if (app_urls_.empty() && base::MessageLoop::current()->is_running()) {
300 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
301 task_runners_->shell_runner());
302 if (app_complete_callback_.is_null()) {
303 base::MessageLoop::current()->Quit();
304 } else {
305 app_complete_callback_.Run();
311 } // namespace runner
312 } // namespace mojo