Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / mojo / runner / context.cc
blob5510ffd3cc084132fa3426e5526ffd2052373b5b
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/in_process_native_runner.h"
33 #include "mojo/runner/out_of_process_native_runner.h"
34 #include "mojo/runner/switches.h"
35 #include "mojo/services/tracing/tracing.mojom.h"
36 #include "mojo/shell/application_loader.h"
37 #include "mojo/shell/application_manager.h"
38 #include "mojo/shell/switches.h"
39 #include "mojo/util/filename_util.h"
40 #include "url/gurl.h"
42 namespace mojo {
43 namespace runner {
44 namespace {
46 // Used to ensure we only init once.
47 class Setup {
48 public:
49 Setup() {
50 embedder::Init(make_scoped_ptr(new embedder::SimplePlatformSupport()));
53 ~Setup() {}
55 private:
56 DISALLOW_COPY_AND_ASSIGN(Setup);
59 bool ConfigureURLMappings(const base::CommandLine& command_line,
60 Context* context) {
61 URLResolver* resolver = context->url_resolver();
63 // Configure the resolution of unknown mojo: URLs.
64 GURL base_url;
65 if (command_line.HasSwitch(switches::kOrigin)) {
66 base_url = GURL(command_line.GetSwitchValueASCII(switches::kOrigin));
67 } else if (!command_line.HasSwitch(switches::kUseUpdater)) {
68 // Use the shell's file root if the base was not specified.
69 base_url = context->ResolveShellFileURL("");
72 if (base_url.is_valid())
73 resolver->SetMojoBaseURL(base_url);
75 // The network service and updater must be loaded from the filesystem.
76 // This mapping is done before the command line URL mapping are processed, so
77 // that it can be overridden.
78 resolver->AddURLMapping(GURL("mojo:network_service"),
79 context->ResolveShellFileURL(
80 "file:network_service/network_service.mojo"));
81 resolver->AddURLMapping(
82 GURL("mojo:updater"),
83 context->ResolveShellFileURL("file:updater/updater.mojo"));
85 // Command line URL mapping.
86 std::vector<URLResolver::OriginMapping> origin_mappings =
87 URLResolver::GetOriginMappings(command_line.argv());
88 for (const auto& origin_mapping : origin_mappings)
89 resolver->AddOriginMapping(GURL(origin_mapping.origin),
90 GURL(origin_mapping.base_url));
92 if (command_line.HasSwitch(switches::kURLMappings)) {
93 const std::string mappings =
94 command_line.GetSwitchValueASCII(switches::kURLMappings);
96 base::StringPairs pairs;
97 if (!base::SplitStringIntoKeyValuePairs(mappings, '=', ',', &pairs))
98 return false;
99 using StringPair = std::pair<std::string, std::string>;
100 for (const StringPair& pair : pairs) {
101 const GURL from(pair.first);
102 const GURL to = context->ResolveCommandLineURL(pair.second);
103 if (!from.is_valid() || !to.is_valid())
104 return false;
105 resolver->AddURLMapping(from, to);
109 return true;
112 void InitContentHandlers(shell::ApplicationManager* manager,
113 const base::CommandLine& command_line) {
114 // Default content handlers.
115 manager->RegisterContentHandler("application/pdf", GURL("mojo:pdf_viewer"));
116 manager->RegisterContentHandler("image/png", GURL("mojo:png_viewer"));
117 manager->RegisterContentHandler("text/html", GURL("mojo:html_viewer"));
119 // Command-line-specified content handlers.
120 std::string handlers_spec =
121 command_line.GetSwitchValueASCII(switches::kContentHandlers);
122 if (handlers_spec.empty())
123 return;
125 #if defined(OS_ANDROID)
126 // TODO(eseidel): On Android we pass command line arguments is via the
127 // 'parameters' key on the intent, which we specify during 'am shell start'
128 // via --esa, however that expects comma-separated values and says:
129 // am shell --help:
130 // [--esa <EXTRA_KEY> <EXTRA_STRING_VALUE>[,<EXTRA_STRING_VALUE...]]
131 // (to embed a comma into a string escape it using "\,")
132 // Whatever takes 'parameters' and constructs a CommandLine is failing to
133 // un-escape the commas, we need to move this fix to that file.
134 base::ReplaceSubstringsAfterOffset(&handlers_spec, 0, "\\,", ",");
135 #endif
137 std::vector<std::string> parts;
138 base::SplitString(handlers_spec, ',', &parts);
139 if (parts.size() % 2 != 0) {
140 LOG(ERROR) << "Invalid value for switch " << switches::kContentHandlers
141 << ": must be a comma-separated list of mimetype/url pairs."
142 << handlers_spec;
143 return;
146 for (size_t i = 0; i < parts.size(); i += 2) {
147 GURL url(parts[i + 1]);
148 if (!url.is_valid()) {
149 LOG(ERROR) << "Invalid value for switch " << switches::kContentHandlers
150 << ": '" << parts[i + 1] << "' is not a valid URL.";
151 return;
153 // TODO(eseidel): We should also validate that the mimetype is valid
154 // net/base/mime_util.h could do this, but we don't want to depend on net.
155 manager->RegisterContentHandler(parts[i], url);
159 void InitNativeOptions(shell::ApplicationManager* manager,
160 const base::CommandLine& command_line) {
161 std::vector<std::string> force_in_process_url_list;
162 base::SplitString(command_line.GetSwitchValueASCII(switches::kForceInProcess),
163 ',', &force_in_process_url_list);
164 for (const auto& force_in_process_url : force_in_process_url_list) {
165 GURL gurl(force_in_process_url);
166 if (!gurl.is_valid()) {
167 LOG(ERROR) << "Invalid value for switch " << switches::kForceInProcess
168 << ": '" << force_in_process_url << "'is not a valid URL.";
169 return;
172 shell::NativeRunnerFactory::Options options;
173 options.force_in_process = true;
174 manager->SetNativeOptionsForURL(options, gurl);
178 void InitDevToolsServiceIfNeeded(shell::ApplicationManager* manager,
179 const base::CommandLine& command_line) {
180 if (!command_line.HasSwitch(devtools_service::kRemoteDebuggingPort))
181 return;
183 std::string port_str =
184 command_line.GetSwitchValueASCII(devtools_service::kRemoteDebuggingPort);
185 unsigned port;
186 if (!base::StringToUint(port_str, &port) || port > 65535) {
187 LOG(ERROR) << "Invalid value for switch "
188 << devtools_service::kRemoteDebuggingPort << ": '" << port_str
189 << "' is not a valid port number.";
190 return;
193 ServiceProviderPtr devtools_service_provider;
194 URLRequestPtr request(URLRequest::New());
195 request->url = "mojo:devtools_service";
196 manager->ConnectToApplication(
197 nullptr, request.Pass(), std::string(), GURL("mojo:shell"),
198 GetProxy(&devtools_service_provider), nullptr, nullptr, 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(), nullptr, base::Closure());
315 InitDevToolsServiceIfNeeded(&application_manager_, command_line);
317 return true;
320 void Context::Shutdown() {
321 TRACE_EVENT0("mojo_shell", "Context::Shutdown");
322 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
323 task_runners_->shell_runner());
324 embedder::ShutdownIPCSupport();
325 // We'll quit when we get OnShutdownComplete().
326 base::MessageLoop::current()->Run();
329 GURL Context::ResolveMappings(const GURL& url) {
330 return url_resolver_.ApplyMappings(url);
333 GURL Context::ResolveMojoURL(const GURL& url) {
334 return url_resolver_.ResolveMojoURL(url);
337 bool Context::CreateFetcher(
338 const GURL& url,
339 const shell::Fetcher::FetchCallback& loader_callback) {
340 return false;
343 void Context::OnShutdownComplete() {
344 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
345 task_runners_->shell_runner());
346 base::MessageLoop::current()->Quit();
349 void Context::Run(const GURL& url) {
350 DCHECK(app_complete_callback_.is_null());
351 ServiceProviderPtr services;
352 ServiceProviderPtr exposed_services;
354 app_urls_.insert(url);
355 mojo::URLRequestPtr request(mojo::URLRequest::New());
356 request->url = mojo::String::From(url.spec());
357 application_manager_.ConnectToApplication(
358 nullptr, request.Pass(), std::string(), GURL(), GetProxy(&services),
359 exposed_services.Pass(), nullptr,
360 base::Bind(&Context::OnApplicationEnd, base::Unretained(this), url));
363 void Context::RunCommandLineApplication(const base::Closure& callback) {
364 DCHECK(app_urls_.empty());
365 DCHECK(app_complete_callback_.is_null());
366 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
367 base::CommandLine::StringVector args = command_line->GetArgs();
368 for (size_t i = 0; i < args.size(); ++i) {
369 GURL possible_app(args[i]);
370 if (possible_app.SchemeIs("mojo")) {
371 Run(possible_app);
372 app_complete_callback_ = callback;
373 break;
378 void Context::OnApplicationEnd(const GURL& url) {
379 if (app_urls_.find(url) != app_urls_.end()) {
380 app_urls_.erase(url);
381 if (app_urls_.empty() && base::MessageLoop::current()->is_running()) {
382 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
383 task_runners_->shell_runner());
384 if (app_complete_callback_.is_null()) {
385 base::MessageLoop::current()->Quit();
386 } else {
387 app_complete_callback_.Run();
393 } // namespace runner
394 } // namespace mojo