Update broken references to image assets
[chromium-blink-merge.git] / mojo / runner / context.cc
blob73464b671030a2cf5b8f5b34686af524c074f326
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/memory/scoped_vector.h"
16 #include "base/path_service.h"
17 #include "base/process/process_info.h"
18 #include "base/run_loop.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/strings/string_split.h"
21 #include "base/strings/string_util.h"
22 #include "base/trace_event/trace_event.h"
23 #include "build/build_config.h"
24 #include "components/devtools_service/public/cpp/switches.h"
25 #include "components/devtools_service/public/interfaces/devtools_service.mojom.h"
26 #include "mojo/application/public/cpp/application_connection.h"
27 #include "mojo/application/public/cpp/application_delegate.h"
28 #include "mojo/application/public/cpp/application_impl.h"
29 #include "mojo/common/trace_controller_impl.h"
30 #include "mojo/common/tracing_impl.h"
31 #include "mojo/edk/embedder/embedder.h"
32 #include "mojo/edk/embedder/simple_platform_support.h"
33 #include "mojo/runner/about_fetcher.h"
34 #include "mojo/runner/in_process_native_runner.h"
35 #include "mojo/runner/out_of_process_native_runner.h"
36 #include "mojo/runner/switches.h"
37 #include "mojo/services/tracing/public/cpp/switches.h"
38 #include "mojo/services/tracing/public/interfaces/tracing.mojom.h"
39 #include "mojo/shell/application_loader.h"
40 #include "mojo/shell/application_manager.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 bool ConfigureURLMappings(const base::CommandLine& command_line,
63 Context* context) {
64 URLResolver* resolver = context->url_resolver();
66 // Configure the resolution of unknown mojo: URLs.
67 GURL base_url;
68 if (!command_line.HasSwitch(switches::kUseUpdater)) {
69 // Use the shell's file root if the base was not specified.
70 base_url = context->ResolveShellFileURL(std::string());
73 if (base_url.is_valid())
74 resolver->SetMojoBaseURL(base_url);
76 // The network service and updater must be loaded from the filesystem.
77 // This mapping is done before the command line URL mapping are processed, so
78 // that it can be overridden.
79 resolver->AddURLMapping(GURL("mojo:network_service"),
80 context->ResolveShellFileURL(
81 "file:network_service/network_service.mojo"));
82 resolver->AddURLMapping(
83 GURL("mojo:updater"),
84 context->ResolveShellFileURL("file:updater/updater.mojo"));
86 // Command line URL mapping.
87 std::vector<URLResolver::OriginMapping> origin_mappings =
88 URLResolver::GetOriginMappings(command_line.argv());
89 for (const auto& origin_mapping : origin_mappings)
90 resolver->AddOriginMapping(GURL(origin_mapping.origin),
91 GURL(origin_mapping.base_url));
93 if (command_line.HasSwitch(switches::kURLMappings)) {
94 const std::string mappings =
95 command_line.GetSwitchValueASCII(switches::kURLMappings);
97 base::StringPairs pairs;
98 if (!base::SplitStringIntoKeyValuePairs(mappings, '=', ',', &pairs))
99 return false;
100 using StringPair = std::pair<std::string, std::string>;
101 for (const StringPair& pair : pairs) {
102 const GURL from(pair.first);
103 const GURL to = context->ResolveCommandLineURL(pair.second);
104 if (!from.is_valid() || !to.is_valid())
105 return false;
106 resolver->AddURLMapping(from, to);
110 return true;
113 void InitContentHandlers(shell::ApplicationManager* manager,
114 const base::CommandLine& command_line) {
115 // Default content handlers.
116 manager->RegisterContentHandler("application/pdf", GURL("mojo:pdf_viewer"));
117 manager->RegisterContentHandler("image/png", GURL("mojo:png_viewer"));
118 manager->RegisterContentHandler("text/html", GURL("mojo:html_viewer"));
120 // Command-line-specified content handlers.
121 std::string handlers_spec =
122 command_line.GetSwitchValueASCII(switches::kContentHandlers);
123 if (handlers_spec.empty())
124 return;
126 #if defined(OS_ANDROID)
127 // TODO(eseidel): On Android we pass command line arguments is via the
128 // 'parameters' key on the intent, which we specify during 'am shell start'
129 // via --esa, however that expects comma-separated values and says:
130 // am shell --help:
131 // [--esa <EXTRA_KEY> <EXTRA_STRING_VALUE>[,<EXTRA_STRING_VALUE...]]
132 // (to embed a comma into a string escape it using "\,")
133 // Whatever takes 'parameters' and constructs a CommandLine is failing to
134 // un-escape the commas, we need to move this fix to that file.
135 base::ReplaceSubstringsAfterOffset(&handlers_spec, 0, "\\,", ",");
136 #endif
138 std::vector<std::string> parts = base::SplitString(
139 handlers_spec, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
140 if (parts.size() % 2 != 0) {
141 LOG(ERROR) << "Invalid value for switch " << switches::kContentHandlers
142 << ": must be a comma-separated list of mimetype/url pairs."
143 << handlers_spec;
144 return;
147 for (size_t i = 0; i < parts.size(); i += 2) {
148 GURL url(parts[i + 1]);
149 if (!url.is_valid()) {
150 LOG(ERROR) << "Invalid value for switch " << switches::kContentHandlers
151 << ": '" << parts[i + 1] << "' is not a valid URL.";
152 return;
154 // TODO(eseidel): We should also validate that the mimetype is valid
155 // net/base/mime_util.h could do this, but we don't want to depend on net.
156 manager->RegisterContentHandler(parts[i], url);
160 void InitNativeOptions(shell::ApplicationManager* manager,
161 const base::CommandLine& command_line) {
162 std::vector<std::string> force_in_process_url_list = base::SplitString(
163 command_line.GetSwitchValueASCII(switches::kForceInProcess), ",",
164 base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
165 for (const auto& force_in_process_url : force_in_process_url_list) {
166 GURL gurl(force_in_process_url);
167 if (!gurl.is_valid()) {
168 LOG(ERROR) << "Invalid value for switch " << switches::kForceInProcess
169 << ": '" << force_in_process_url << "'is not a valid URL.";
170 return;
173 shell::NativeRunnerFactory::Options options;
174 options.force_in_process = true;
175 manager->SetNativeOptionsForURL(options, gurl);
179 void InitDevToolsServiceIfNeeded(shell::ApplicationManager* manager,
180 const base::CommandLine& command_line) {
181 if (!command_line.HasSwitch(devtools_service::kRemoteDebuggingPort))
182 return;
184 std::string port_str =
185 command_line.GetSwitchValueASCII(devtools_service::kRemoteDebuggingPort);
186 unsigned port;
187 if (!base::StringToUint(port_str, &port) || port > 65535) {
188 LOG(ERROR) << "Invalid value for switch "
189 << devtools_service::kRemoteDebuggingPort << ": '" << port_str
190 << "' is not a valid port number.";
191 return;
194 ServiceProviderPtr devtools_service_provider;
195 URLRequestPtr request(URLRequest::New());
196 request->url = "mojo:devtools_service";
197 manager->ConnectToApplication(
198 nullptr, request.Pass(), std::string(), GURL("mojo:shell"),
199 GetProxy(&devtools_service_provider), nullptr,
200 shell::GetPermissiveCapabilityFilter(), base::Closure());
202 devtools_service::DevToolsCoordinatorPtr devtools_coordinator;
203 devtools_service_provider->ConnectToService(
204 devtools_service::DevToolsCoordinator::Name_,
205 GetProxy(&devtools_coordinator).PassMessagePipe());
206 devtools_coordinator->Initialize(static_cast<uint16_t>(port));
209 class TracingServiceProvider : public ServiceProvider {
210 public:
211 explicit TracingServiceProvider(InterfaceRequest<ServiceProvider> request)
212 : binding_(this, request.Pass()) {}
213 ~TracingServiceProvider() override {}
215 void ConnectToService(const String& service_name,
216 ScopedMessagePipeHandle client_handle) override {
217 if (service_name == tracing::TraceController::Name_) {
218 new TraceControllerImpl(
219 MakeRequest<tracing::TraceController>(client_handle.Pass()));
223 private:
224 StrongBinding<ServiceProvider> binding_;
226 DISALLOW_COPY_AND_ASSIGN(TracingServiceProvider);
229 } // namespace
231 Context::Context() : application_manager_(this) {
232 DCHECK(!base::MessageLoop::current());
234 // By default assume that the local apps reside alongside the shell.
235 // TODO(ncbray): really, this should be passed in rather than defaulting.
236 // This default makes sense for desktop but not Android.
237 base::FilePath shell_dir;
238 PathService::Get(base::DIR_MODULE, &shell_dir);
239 SetShellFileRoot(shell_dir);
241 base::FilePath cwd;
242 PathService::Get(base::DIR_CURRENT, &cwd);
243 SetCommandLineCWD(cwd);
246 Context::~Context() {
247 DCHECK(!base::MessageLoop::current());
250 // static
251 void Context::EnsureEmbedderIsInitialized() {
252 static base::LazyInstance<Setup>::Leaky setup = LAZY_INSTANCE_INITIALIZER;
253 setup.Get();
256 void Context::SetShellFileRoot(const base::FilePath& path) {
257 shell_file_root_ =
258 util::AddTrailingSlashIfNeeded(util::FilePathToFileURL(path));
261 GURL Context::ResolveShellFileURL(const std::string& path) {
262 return shell_file_root_.Resolve(path);
265 void Context::SetCommandLineCWD(const base::FilePath& path) {
266 command_line_cwd_ =
267 util::AddTrailingSlashIfNeeded(util::FilePathToFileURL(path));
270 GURL Context::ResolveCommandLineURL(const std::string& path) {
271 return command_line_cwd_.Resolve(path);
274 bool Context::Init() {
275 TRACE_EVENT0("mojo_shell", "Context::Init");
276 const base::CommandLine& command_line =
277 *base::CommandLine::ForCurrentProcess();
279 EnsureEmbedderIsInitialized();
280 task_runners_.reset(
281 new TaskRunners(base::MessageLoop::current()->task_runner()));
283 // TODO(vtl): Probably these failures should be checked before |Init()|, and
284 // this function simply shouldn't fail.
285 if (!shell_file_root_.is_valid())
286 return false;
287 if (!ConfigureURLMappings(command_line, this))
288 return false;
290 // TODO(vtl): This should be MASTER, not NONE.
291 embedder::InitIPCSupport(
292 embedder::ProcessType::NONE, task_runners_->shell_runner(), this,
293 task_runners_->io_runner(), embedder::ScopedPlatformHandle());
295 scoped_ptr<shell::NativeRunnerFactory> runner_factory;
296 if (command_line.HasSwitch(switches::kEnableMultiprocess))
297 runner_factory.reset(new OutOfProcessNativeRunnerFactory(this));
298 else
299 runner_factory.reset(new InProcessNativeRunnerFactory(this));
300 application_manager_.set_blocking_pool(task_runners_->blocking_pool());
301 application_manager_.set_native_runner_factory(runner_factory.Pass());
302 application_manager_.set_disable_cache(
303 base::CommandLine::ForCurrentProcess()->HasSwitch(
304 switches::kDisableCache));
306 InitContentHandlers(&application_manager_, command_line);
307 InitNativeOptions(&application_manager_, command_line);
309 ServiceProviderPtr service_provider_ptr;
310 ServiceProviderPtr tracing_service_provider_ptr;
311 new TracingServiceProvider(GetProxy(&tracing_service_provider_ptr));
312 mojo::URLRequestPtr request(mojo::URLRequest::New());
313 request->url = mojo::String::From("mojo:tracing");
314 application_manager_.ConnectToApplication(
315 nullptr, request.Pass(), std::string(), GURL(),
316 GetProxy(&service_provider_ptr), tracing_service_provider_ptr.Pass(),
317 shell::GetPermissiveCapabilityFilter(), base::Closure());
319 // CurrentProcessInfo::CreationTime() is missing on some platforms.
320 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
321 // Record the shell process creation time for performance testing.
322 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
323 tracing::kEnableStatsCollectionBindings)) {
324 tracing::StartupPerformanceDataCollectorPtr collector;
325 service_provider_ptr->ConnectToService(
326 tracing::StartupPerformanceDataCollector::Name_,
327 GetProxy(&collector).PassMessagePipe());
328 const base::Time creation_time = base::CurrentProcessInfo::CreationTime();
329 collector->SetShellProcessCreationTime(creation_time.ToInternalValue());
331 #endif
333 InitDevToolsServiceIfNeeded(&application_manager_, command_line);
335 return true;
338 void Context::Shutdown() {
339 TRACE_EVENT0("mojo_shell", "Context::Shutdown");
340 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
341 task_runners_->shell_runner());
342 embedder::ShutdownIPCSupport();
343 // We'll quit when we get OnShutdownComplete().
344 base::MessageLoop::current()->Run();
347 GURL Context::ResolveMappings(const GURL& url) {
348 return url_resolver_.ApplyMappings(url);
351 GURL Context::ResolveMojoURL(const GURL& url) {
352 return url_resolver_.ResolveMojoURL(url);
355 bool Context::CreateFetcher(
356 const GURL& url,
357 const shell::Fetcher::FetchCallback& loader_callback) {
358 if (url.SchemeIs(AboutFetcher::kAboutScheme)) {
359 AboutFetcher::Start(url, loader_callback);
360 return true;
363 return false;
366 void Context::OnShutdownComplete() {
367 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
368 task_runners_->shell_runner());
369 base::MessageLoop::current()->Quit();
372 void Context::Run(const GURL& url) {
373 DCHECK(app_complete_callback_.is_null());
374 ServiceProviderPtr services;
375 ServiceProviderPtr exposed_services;
377 app_urls_.insert(url);
378 mojo::URLRequestPtr request(mojo::URLRequest::New());
379 request->url = mojo::String::From(url.spec());
380 application_manager_.ConnectToApplication(
381 nullptr, request.Pass(), std::string(), GURL(), GetProxy(&services),
382 exposed_services.Pass(), shell::GetPermissiveCapabilityFilter(),
383 base::Bind(&Context::OnApplicationEnd, base::Unretained(this), url));
386 void Context::RunCommandLineApplication(const base::Closure& callback) {
387 DCHECK(app_urls_.empty());
388 DCHECK(app_complete_callback_.is_null());
389 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
390 base::CommandLine::StringVector args = command_line->GetArgs();
391 for (size_t i = 0; i < args.size(); ++i) {
392 GURL possible_app(args[i]);
393 if (possible_app.SchemeIs("mojo")) {
394 Run(possible_app);
395 app_complete_callback_ = callback;
396 break;
401 void Context::OnApplicationEnd(const GURL& url) {
402 if (app_urls_.find(url) != app_urls_.end()) {
403 app_urls_.erase(url);
404 if (app_urls_.empty() && base::MessageLoop::current()->is_running()) {
405 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
406 task_runners_->shell_runner());
407 if (app_complete_callback_.is_null()) {
408 base::MessageLoop::current()->Quit();
409 } else {
410 app_complete_callback_.Run();
416 } // namespace runner
417 } // namespace mojo