Correctly reset theme color on NTP.
[chromium-blink-merge.git] / mojo / runner / context.cc
blob40c62772cdaa23706a034b7670a9624a915595ae
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/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/runner/about_fetcher.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/tracing.mojom.h"
37 #include "mojo/shell/application_loader.h"
38 #include "mojo/shell/application_manager.h"
39 #include "mojo/shell/switches.h"
40 #include "mojo/util/filename_util.h"
41 #include "url/gurl.h"
43 namespace mojo {
44 namespace runner {
45 namespace {
47 // Used to ensure we only init once.
48 class Setup {
49 public:
50 Setup() {
51 embedder::Init(make_scoped_ptr(new embedder::SimplePlatformSupport()));
54 ~Setup() {}
56 private:
57 DISALLOW_COPY_AND_ASSIGN(Setup);
60 bool ConfigureURLMappings(const base::CommandLine& command_line,
61 Context* context) {
62 URLResolver* resolver = context->url_resolver();
64 // Configure the resolution of unknown mojo: URLs.
65 GURL base_url;
66 if (!command_line.HasSwitch(switches::kUseUpdater)) {
67 // Use the shell's file root if the base was not specified.
68 base_url = context->ResolveShellFileURL(std::string());
71 if (base_url.is_valid())
72 resolver->SetMojoBaseURL(base_url);
74 // The network service and updater must be loaded from the filesystem.
75 // This mapping is done before the command line URL mapping are processed, so
76 // that it can be overridden.
77 resolver->AddURLMapping(GURL("mojo:network_service"),
78 context->ResolveShellFileURL(
79 "file:network_service/network_service.mojo"));
80 resolver->AddURLMapping(
81 GURL("mojo:updater"),
82 context->ResolveShellFileURL("file:updater/updater.mojo"));
84 // Command line URL mapping.
85 std::vector<URLResolver::OriginMapping> origin_mappings =
86 URLResolver::GetOriginMappings(command_line.argv());
87 for (const auto& origin_mapping : origin_mappings)
88 resolver->AddOriginMapping(GURL(origin_mapping.origin),
89 GURL(origin_mapping.base_url));
91 if (command_line.HasSwitch(switches::kURLMappings)) {
92 const std::string mappings =
93 command_line.GetSwitchValueASCII(switches::kURLMappings);
95 base::StringPairs pairs;
96 if (!base::SplitStringIntoKeyValuePairs(mappings, '=', ',', &pairs))
97 return false;
98 using StringPair = std::pair<std::string, std::string>;
99 for (const StringPair& pair : pairs) {
100 const GURL from(pair.first);
101 const GURL to = context->ResolveCommandLineURL(pair.second);
102 if (!from.is_valid() || !to.is_valid())
103 return false;
104 resolver->AddURLMapping(from, to);
108 return true;
111 void InitContentHandlers(shell::ApplicationManager* manager,
112 const base::CommandLine& command_line) {
113 // Default content handlers.
114 manager->RegisterContentHandler("application/pdf", GURL("mojo:pdf_viewer"));
115 manager->RegisterContentHandler("image/png", GURL("mojo:png_viewer"));
116 manager->RegisterContentHandler("text/html", GURL("mojo:html_viewer"));
118 // Command-line-specified content handlers.
119 std::string handlers_spec =
120 command_line.GetSwitchValueASCII(switches::kContentHandlers);
121 if (handlers_spec.empty())
122 return;
124 #if defined(OS_ANDROID)
125 // TODO(eseidel): On Android we pass command line arguments is via the
126 // 'parameters' key on the intent, which we specify during 'am shell start'
127 // via --esa, however that expects comma-separated values and says:
128 // am shell --help:
129 // [--esa <EXTRA_KEY> <EXTRA_STRING_VALUE>[,<EXTRA_STRING_VALUE...]]
130 // (to embed a comma into a string escape it using "\,")
131 // Whatever takes 'parameters' and constructs a CommandLine is failing to
132 // un-escape the commas, we need to move this fix to that file.
133 base::ReplaceSubstringsAfterOffset(&handlers_spec, 0, "\\,", ",");
134 #endif
136 std::vector<std::string> parts = base::SplitString(
137 handlers_spec, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
138 if (parts.size() % 2 != 0) {
139 LOG(ERROR) << "Invalid value for switch " << switches::kContentHandlers
140 << ": must be a comma-separated list of mimetype/url pairs."
141 << handlers_spec;
142 return;
145 for (size_t i = 0; i < parts.size(); i += 2) {
146 GURL url(parts[i + 1]);
147 if (!url.is_valid()) {
148 LOG(ERROR) << "Invalid value for switch " << switches::kContentHandlers
149 << ": '" << parts[i + 1] << "' is not a valid URL.";
150 return;
152 // TODO(eseidel): We should also validate that the mimetype is valid
153 // net/base/mime_util.h could do this, but we don't want to depend on net.
154 manager->RegisterContentHandler(parts[i], url);
158 void InitNativeOptions(shell::ApplicationManager* manager,
159 const base::CommandLine& command_line) {
160 std::vector<std::string> force_in_process_url_list = base::SplitString(
161 command_line.GetSwitchValueASCII(switches::kForceInProcess), ",",
162 base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
163 for (const auto& force_in_process_url : force_in_process_url_list) {
164 GURL gurl(force_in_process_url);
165 if (!gurl.is_valid()) {
166 LOG(ERROR) << "Invalid value for switch " << switches::kForceInProcess
167 << ": '" << force_in_process_url << "'is not a valid URL.";
168 return;
171 shell::NativeRunnerFactory::Options options;
172 options.force_in_process = true;
173 manager->SetNativeOptionsForURL(options, gurl);
177 void InitDevToolsServiceIfNeeded(shell::ApplicationManager* manager,
178 const base::CommandLine& command_line) {
179 if (!command_line.HasSwitch(devtools_service::kRemoteDebuggingPort))
180 return;
182 std::string port_str =
183 command_line.GetSwitchValueASCII(devtools_service::kRemoteDebuggingPort);
184 unsigned port;
185 if (!base::StringToUint(port_str, &port) || port > 65535) {
186 LOG(ERROR) << "Invalid value for switch "
187 << devtools_service::kRemoteDebuggingPort << ": '" << port_str
188 << "' is not a valid port number.";
189 return;
192 ServiceProviderPtr devtools_service_provider;
193 URLRequestPtr request(URLRequest::New());
194 request->url = "mojo:devtools_service";
195 manager->ConnectToApplication(
196 nullptr, request.Pass(), std::string(), GURL("mojo:shell"),
197 GetProxy(&devtools_service_provider), nullptr,
198 shell::GetPermissiveCapabilityFilter(), base::Closure());
200 devtools_service::DevToolsCoordinatorPtr devtools_coordinator;
201 devtools_service_provider->ConnectToService(
202 devtools_service::DevToolsCoordinator::Name_,
203 GetProxy(&devtools_coordinator).PassMessagePipe());
204 devtools_coordinator->Initialize(static_cast<uint16_t>(port));
207 class TracingServiceProvider : public ServiceProvider {
208 public:
209 explicit TracingServiceProvider(InterfaceRequest<ServiceProvider> request)
210 : binding_(this, request.Pass()) {}
211 ~TracingServiceProvider() override {}
213 void ConnectToService(const String& service_name,
214 ScopedMessagePipeHandle client_handle) override {
215 if (service_name == tracing::TraceController::Name_) {
216 new TraceControllerImpl(
217 MakeRequest<tracing::TraceController>(client_handle.Pass()));
221 private:
222 StrongBinding<ServiceProvider> binding_;
224 DISALLOW_COPY_AND_ASSIGN(TracingServiceProvider);
227 } // namespace
229 Context::Context() : application_manager_(this) {
230 DCHECK(!base::MessageLoop::current());
232 // By default assume that the local apps reside alongside the shell.
233 // TODO(ncbray): really, this should be passed in rather than defaulting.
234 // This default makes sense for desktop but not Android.
235 base::FilePath shell_dir;
236 PathService::Get(base::DIR_MODULE, &shell_dir);
237 SetShellFileRoot(shell_dir);
239 base::FilePath cwd;
240 PathService::Get(base::DIR_CURRENT, &cwd);
241 SetCommandLineCWD(cwd);
244 Context::~Context() {
245 DCHECK(!base::MessageLoop::current());
248 // static
249 void Context::EnsureEmbedderIsInitialized() {
250 static base::LazyInstance<Setup>::Leaky setup = LAZY_INSTANCE_INITIALIZER;
251 setup.Get();
254 void Context::SetShellFileRoot(const base::FilePath& path) {
255 shell_file_root_ =
256 util::AddTrailingSlashIfNeeded(util::FilePathToFileURL(path));
259 GURL Context::ResolveShellFileURL(const std::string& path) {
260 return shell_file_root_.Resolve(path);
263 void Context::SetCommandLineCWD(const base::FilePath& path) {
264 command_line_cwd_ =
265 util::AddTrailingSlashIfNeeded(util::FilePathToFileURL(path));
268 GURL Context::ResolveCommandLineURL(const std::string& path) {
269 return command_line_cwd_.Resolve(path);
272 bool Context::Init() {
273 TRACE_EVENT0("mojo_shell", "Context::Init");
274 const base::CommandLine& command_line =
275 *base::CommandLine::ForCurrentProcess();
277 EnsureEmbedderIsInitialized();
278 task_runners_.reset(
279 new TaskRunners(base::MessageLoop::current()->task_runner()));
281 // TODO(vtl): Probably these failures should be checked before |Init()|, and
282 // this function simply shouldn't fail.
283 if (!shell_file_root_.is_valid())
284 return false;
285 if (!ConfigureURLMappings(command_line, this))
286 return false;
288 // TODO(vtl): This should be MASTER, not NONE.
289 embedder::InitIPCSupport(
290 embedder::ProcessType::NONE, task_runners_->shell_runner(), this,
291 task_runners_->io_runner(), embedder::ScopedPlatformHandle());
293 scoped_ptr<shell::NativeRunnerFactory> runner_factory;
294 if (command_line.HasSwitch(switches::kEnableMultiprocess))
295 runner_factory.reset(new OutOfProcessNativeRunnerFactory(this));
296 else
297 runner_factory.reset(new InProcessNativeRunnerFactory(this));
298 application_manager_.set_blocking_pool(task_runners_->blocking_pool());
299 application_manager_.set_native_runner_factory(runner_factory.Pass());
300 application_manager_.set_disable_cache(
301 base::CommandLine::ForCurrentProcess()->HasSwitch(
302 switches::kDisableCache));
304 InitContentHandlers(&application_manager_, command_line);
305 InitNativeOptions(&application_manager_, command_line);
307 ServiceProviderPtr tracing_service_provider_ptr;
308 new TracingServiceProvider(GetProxy(&tracing_service_provider_ptr));
309 mojo::URLRequestPtr request(mojo::URLRequest::New());
310 request->url = mojo::String::From("mojo:tracing");
311 application_manager_.ConnectToApplication(
312 nullptr, request.Pass(), std::string(), GURL(""), nullptr,
313 tracing_service_provider_ptr.Pass(),
314 shell::GetPermissiveCapabilityFilter(), base::Closure());
316 InitDevToolsServiceIfNeeded(&application_manager_, command_line);
318 return true;
321 void Context::Shutdown() {
322 TRACE_EVENT0("mojo_shell", "Context::Shutdown");
323 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
324 task_runners_->shell_runner());
325 embedder::ShutdownIPCSupport();
326 // We'll quit when we get OnShutdownComplete().
327 base::MessageLoop::current()->Run();
330 GURL Context::ResolveMappings(const GURL& url) {
331 return url_resolver_.ApplyMappings(url);
334 GURL Context::ResolveMojoURL(const GURL& url) {
335 return url_resolver_.ResolveMojoURL(url);
338 bool Context::CreateFetcher(
339 const GURL& url,
340 const shell::Fetcher::FetchCallback& loader_callback) {
341 if (url.SchemeIs(AboutFetcher::kAboutScheme)) {
342 AboutFetcher::Start(url, loader_callback);
343 return true;
346 return false;
349 void Context::OnShutdownComplete() {
350 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
351 task_runners_->shell_runner());
352 base::MessageLoop::current()->Quit();
355 void Context::Run(const GURL& url) {
356 DCHECK(app_complete_callback_.is_null());
357 ServiceProviderPtr services;
358 ServiceProviderPtr exposed_services;
360 app_urls_.insert(url);
361 mojo::URLRequestPtr request(mojo::URLRequest::New());
362 request->url = mojo::String::From(url.spec());
363 application_manager_.ConnectToApplication(
364 nullptr, request.Pass(), std::string(), GURL(), GetProxy(&services),
365 exposed_services.Pass(), shell::GetPermissiveCapabilityFilter(),
366 base::Bind(&Context::OnApplicationEnd, base::Unretained(this), url));
369 void Context::RunCommandLineApplication(const base::Closure& callback) {
370 DCHECK(app_urls_.empty());
371 DCHECK(app_complete_callback_.is_null());
372 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
373 base::CommandLine::StringVector args = command_line->GetArgs();
374 for (size_t i = 0; i < args.size(); ++i) {
375 GURL possible_app(args[i]);
376 if (possible_app.SchemeIs("mojo")) {
377 Run(possible_app);
378 app_complete_callback_ = callback;
379 break;
384 void Context::OnApplicationEnd(const GURL& url) {
385 if (app_urls_.find(url) != app_urls_.end()) {
386 app_urls_.erase(url);
387 if (app_urls_.empty() && base::MessageLoop::current()->is_running()) {
388 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
389 task_runners_->shell_runner());
390 if (app_complete_callback_.is_null()) {
391 base::MessageLoop::current()->Quit();
392 } else {
393 app_complete_callback_.Run();
399 } // namespace runner
400 } // namespace mojo