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"
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"
49 // Used to ensure we only init once.
53 embedder::Init(make_scoped_ptr(new embedder::SimplePlatformSupport()));
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())
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:
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, "\\,", ",");
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."
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.";
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
))
115 std::string port_str
=
116 command_line
.GetSwitchValueASCII(devtools_service::kRemoteDebuggingPort
);
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.";
125 ServiceProviderPtr devtools_service_provider
;
126 scoped_ptr
<shell::ConnectToApplicationParams
> params(
127 new shell::ConnectToApplicationParams
);
128 params
->set_source(shell::Identity(GURL("mojo:shell")));
129 params
->SetTargetURL(GURL("mojo:devtools_service"));
130 params
->set_services(GetProxy(&devtools_service_provider
));
131 manager
->ConnectToApplication(params
.Pass());
133 devtools_service::DevToolsCoordinatorPtr devtools_coordinator
;
134 devtools_service_provider
->ConnectToService(
135 devtools_service::DevToolsCoordinator::Name_
,
136 GetProxy(&devtools_coordinator
).PassMessagePipe());
137 devtools_coordinator
->Initialize(static_cast<uint16_t>(port
));
140 class TracingServiceProvider
: public ServiceProvider
{
142 explicit TracingServiceProvider(InterfaceRequest
<ServiceProvider
> request
)
143 : binding_(this, request
.Pass()) {}
144 ~TracingServiceProvider() override
{}
146 void ConnectToService(const String
& service_name
,
147 ScopedMessagePipeHandle client_handle
) override
{
148 if (service_name
== tracing::TraceController::Name_
) {
149 new TraceControllerImpl(
150 MakeRequest
<tracing::TraceController
>(client_handle
.Pass()));
155 StrongBinding
<ServiceProvider
> binding_
;
157 DISALLOW_COPY_AND_ASSIGN(TracingServiceProvider
);
162 Context::Context(const base::FilePath
& shell_file_root
)
163 : shell_file_root_(shell_file_root
),
164 package_manager_(nullptr),
165 main_entry_time_(base::Time::Now()) {}
167 Context::~Context() {
168 DCHECK(!base::MessageLoop::current());
172 void Context::EnsureEmbedderIsInitialized() {
173 static base::LazyInstance
<Setup
>::Leaky setup
= LAZY_INSTANCE_INITIALIZER
;
177 bool Context::Init() {
178 TRACE_EVENT0("mojo_shell", "Context::Init");
179 const base::CommandLine
& command_line
=
180 *base::CommandLine::ForCurrentProcess();
182 EnsureEmbedderIsInitialized();
184 new TaskRunners(base::MessageLoop::current()->task_runner()));
186 // TODO(vtl): This should be MASTER, not NONE.
187 embedder::InitIPCSupport(
188 embedder::ProcessType::NONE
, task_runners_
->shell_runner(), this,
189 task_runners_
->io_runner(), embedder::ScopedPlatformHandle());
191 package_manager_
= new package_manager::PackageManagerImpl(shell_file_root_
);
192 InitContentHandlers(package_manager_
, command_line
);
194 application_manager_
.reset(
195 new shell::ApplicationManager(make_scoped_ptr(package_manager_
)));
197 scoped_ptr
<shell::NativeRunnerFactory
> runner_factory
;
198 if (command_line
.HasSwitch(switches::kEnableMultiprocess
))
199 runner_factory
.reset(new OutOfProcessNativeRunnerFactory(this));
201 runner_factory
.reset(new InProcessNativeRunnerFactory(this));
202 application_manager_
->set_blocking_pool(task_runners_
->blocking_pool());
203 application_manager_
->set_native_runner_factory(runner_factory
.Pass());
205 ServiceProviderPtr service_provider_ptr
;
206 ServiceProviderPtr tracing_service_provider_ptr
;
207 new TracingServiceProvider(GetProxy(&tracing_service_provider_ptr
));
209 scoped_ptr
<shell::ConnectToApplicationParams
> params(
210 new shell::ConnectToApplicationParams
);
211 params
->SetTargetURL(GURL("mojo:tracing"));
212 params
->set_services(GetProxy(&service_provider_ptr
));
213 params
->set_exposed_services(tracing_service_provider_ptr
.Pass());
214 application_manager_
->ConnectToApplication(params
.Pass());
216 // Record the shell startup metrics used for performance testing.
217 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
218 tracing::kEnableStatsCollectionBindings
)) {
219 tracing::StartupPerformanceDataCollectorPtr collector
;
220 service_provider_ptr
->ConnectToService(
221 tracing::StartupPerformanceDataCollector::Name_
,
222 GetProxy(&collector
).PassMessagePipe());
223 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
224 // CurrentProcessInfo::CreationTime is only defined on some platforms.
225 const base::Time creation_time
= base::CurrentProcessInfo::CreationTime();
226 collector
->SetShellProcessCreationTime(creation_time
.ToInternalValue());
228 collector
->SetShellMainEntryPointTime(main_entry_time_
.ToInternalValue());
231 InitDevToolsServiceIfNeeded(application_manager_
.get(), command_line
);
236 void Context::Shutdown() {
237 // Actions triggered by ApplicationManager's destructor may require a current
238 // message loop, so we should destruct it explicitly now as ~Context() occurs
239 // post message loop shutdown.
240 application_manager_
.reset();
242 TRACE_EVENT0("mojo_shell", "Context::Shutdown");
243 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
244 task_runners_
->shell_runner());
245 embedder::ShutdownIPCSupport();
246 // We'll quit when we get OnShutdownComplete().
247 base::MessageLoop::current()->Run();
250 void Context::OnShutdownComplete() {
251 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
252 task_runners_
->shell_runner());
253 base::MessageLoop::current()->Quit();
256 void Context::Run(const GURL
& url
) {
257 DCHECK(app_complete_callback_
.is_null());
258 ServiceProviderPtr services
;
259 ServiceProviderPtr exposed_services
;
261 app_urls_
.insert(url
);
263 scoped_ptr
<shell::ConnectToApplicationParams
> params(
264 new shell::ConnectToApplicationParams
);
265 params
->SetTargetURL(url
);
266 params
->set_services(GetProxy(&services
));
267 params
->set_exposed_services(exposed_services
.Pass());
268 params
->set_on_application_end(
269 base::Bind(&Context::OnApplicationEnd
, base::Unretained(this), url
));
270 application_manager_
->ConnectToApplication(params
.Pass());
273 void Context::RunCommandLineApplication(const base::Closure
& callback
) {
274 DCHECK(app_urls_
.empty());
275 DCHECK(app_complete_callback_
.is_null());
276 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
277 base::CommandLine::StringVector args
= command_line
->GetArgs();
278 for (size_t i
= 0; i
< args
.size(); ++i
) {
279 GURL
possible_app(args
[i
]);
280 if (possible_app
.SchemeIs("mojo")) {
282 app_complete_callback_
= callback
;
288 void Context::OnApplicationEnd(const GURL
& url
) {
289 if (app_urls_
.find(url
) != app_urls_
.end()) {
290 app_urls_
.erase(url
);
291 if (app_urls_
.empty() && base::MessageLoop::current()->is_running()) {
292 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
293 task_runners_
->shell_runner());
294 if (app_complete_callback_
.is_null()) {
295 base::MessageLoop::current()->Quit();
297 app_complete_callback_
.Run();
303 } // namespace runner