[remoting-test] Fix It2Me browser test failures.
[chromium-blink-merge.git] / apps / launcher.cc
blobd5ca7921c6a19905384de5f1555f861956d80cb1
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 "apps/launcher.h"
7 #include <set>
8 #include <utility>
10 #include "base/command_line.h"
11 #include "base/files/file_path.h"
12 #include "base/files/file_util.h"
13 #include "base/logging.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "chrome/browser/extensions/api/file_handlers/app_file_handler_util.h"
18 #include "chrome/browser/extensions/api/file_handlers/mime_util.h"
19 #include "chrome/browser/extensions/api/file_system/file_system_api.h"
20 #include "chrome/browser/profiles/profile.h"
21 #include "content/public/browser/browser_thread.h"
22 #include "content/public/browser/render_process_host.h"
23 #include "content/public/browser/web_contents.h"
24 #include "content/public/common/content_switches.h"
25 #include "content/public/common/url_constants.h"
26 #include "extensions/browser/api/app_runtime/app_runtime_api.h"
27 #include "extensions/browser/event_router.h"
28 #include "extensions/browser/extension_host.h"
29 #include "extensions/browser/extension_prefs.h"
30 #include "extensions/browser/extension_registry.h"
31 #include "extensions/browser/granted_file_entry.h"
32 #include "extensions/browser/lazy_background_task_queue.h"
33 #include "extensions/browser/process_manager.h"
34 #include "extensions/common/api/app_runtime.h"
35 #include "extensions/common/extension.h"
36 #include "extensions/common/manifest_handlers/kiosk_mode_info.h"
37 #include "net/base/filename_util.h"
38 #include "net/base/net_util.h"
39 #include "url/gurl.h"
41 #if defined(OS_CHROMEOS)
42 #include "components/user_manager/user_manager.h"
43 #endif
45 namespace app_runtime = extensions::core_api::app_runtime;
47 using content::BrowserThread;
48 using extensions::AppRuntimeEventRouter;
49 using extensions::app_file_handler_util::CreateFileEntry;
50 using extensions::app_file_handler_util::FileHandlerCanHandleFile;
51 using extensions::app_file_handler_util::FileHandlerForId;
52 using extensions::app_file_handler_util::FirstFileHandlerForFile;
53 using extensions::app_file_handler_util::HasFileSystemWritePermission;
54 using extensions::app_file_handler_util::PrepareFilesForWritableApp;
55 using extensions::EventRouter;
56 using extensions::Extension;
57 using extensions::ExtensionHost;
58 using extensions::GrantedFileEntry;
60 namespace apps {
62 namespace {
64 const char kFallbackMimeType[] = "application/octet-stream";
66 bool DoMakePathAbsolute(const base::FilePath& current_directory,
67 base::FilePath* file_path) {
68 DCHECK(file_path);
69 if (file_path->IsAbsolute())
70 return true;
72 if (current_directory.empty()) {
73 base::FilePath absolute_path = base::MakeAbsoluteFilePath(*file_path);
74 if (absolute_path.empty())
75 return false;
76 *file_path = absolute_path;
77 return true;
80 if (!current_directory.IsAbsolute())
81 return false;
83 *file_path = current_directory.Append(*file_path);
84 return true;
87 // Class to handle launching of platform apps to open specific paths.
88 // An instance of this class is created for each launch. The lifetime of these
89 // instances is managed by reference counted pointers. As long as an instance
90 // has outstanding tasks on a message queue it will be retained; once all
91 // outstanding tasks are completed it will be deleted.
92 class PlatformAppPathLauncher
93 : public base::RefCountedThreadSafe<PlatformAppPathLauncher> {
94 public:
95 PlatformAppPathLauncher(Profile* profile,
96 const Extension* extension,
97 const std::vector<base::FilePath>& file_paths)
98 : profile_(profile),
99 extension_id(extension->id()),
100 file_paths_(file_paths),
101 collector_(profile) {}
103 PlatformAppPathLauncher(Profile* profile,
104 const Extension* extension,
105 const base::FilePath& file_path)
106 : profile_(profile), extension_id(extension->id()), collector_(profile) {
107 if (!file_path.empty())
108 file_paths_.push_back(file_path);
111 void Launch() {
112 DCHECK_CURRENTLY_ON(BrowserThread::UI);
114 const Extension* extension = GetExtension();
115 if (!extension)
116 return;
118 if (file_paths_.empty()) {
119 LaunchWithNoLaunchData();
120 return;
123 for (size_t i = 0; i < file_paths_.size(); ++i) {
124 DCHECK(file_paths_[i].IsAbsolute());
127 if (HasFileSystemWritePermission(extension)) {
128 PrepareFilesForWritableApp(
129 file_paths_,
130 profile_,
131 false,
132 base::Bind(&PlatformAppPathLauncher::OnFilesValid, this),
133 base::Bind(&PlatformAppPathLauncher::OnFilesInvalid, this));
134 return;
137 OnFilesValid();
140 void LaunchWithHandler(const std::string& handler_id) {
141 handler_id_ = handler_id;
142 Launch();
145 void LaunchWithRelativePath(const base::FilePath& current_directory) {
146 BrowserThread::PostTask(
147 BrowserThread::FILE,
148 FROM_HERE,
149 base::Bind(&PlatformAppPathLauncher::MakePathAbsolute,
150 this,
151 current_directory));
154 private:
155 friend class base::RefCountedThreadSafe<PlatformAppPathLauncher>;
157 virtual ~PlatformAppPathLauncher() {}
159 void MakePathAbsolute(const base::FilePath& current_directory) {
160 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
162 for (std::vector<base::FilePath>::iterator it = file_paths_.begin();
163 it != file_paths_.end();
164 ++it) {
165 if (!DoMakePathAbsolute(current_directory, &*it)) {
166 LOG(WARNING) << "Cannot make absolute path from " << it->value();
167 BrowserThread::PostTask(
168 BrowserThread::UI,
169 FROM_HERE,
170 base::Bind(&PlatformAppPathLauncher::LaunchWithNoLaunchData, this));
171 return;
175 BrowserThread::PostTask(BrowserThread::UI,
176 FROM_HERE,
177 base::Bind(&PlatformAppPathLauncher::Launch, this));
180 void OnFilesValid() {
181 collector_.CollectForLocalPaths(
182 file_paths_,
183 base::Bind(&PlatformAppPathLauncher::OnMimeTypesCollected, this));
186 void OnFilesInvalid(const base::FilePath& /* error_path */) {
187 LaunchWithNoLaunchData();
190 void LaunchWithNoLaunchData() {
191 // This method is required as an entry point on the UI thread.
192 DCHECK_CURRENTLY_ON(BrowserThread::UI);
194 const Extension* extension = GetExtension();
195 if (!extension)
196 return;
198 AppRuntimeEventRouter::DispatchOnLaunchedEvent(
199 profile_, extension, extensions::SOURCE_FILE_HANDLER);
202 void OnMimeTypesCollected(scoped_ptr<std::vector<std::string> > mime_types) {
203 DCHECK(file_paths_.size() == mime_types->size());
205 const Extension* extension = GetExtension();
206 if (!extension)
207 return;
209 // If fetching a mime type failed, then use a fallback one.
210 for (size_t i = 0; i < mime_types->size(); ++i) {
211 const std::string mime_type =
212 !(*mime_types)[i].empty() ? (*mime_types)[i] : kFallbackMimeType;
213 mime_types_.push_back(mime_type);
216 // Find file handler from the platform app for the file being opened.
217 const extensions::FileHandlerInfo* handler = NULL;
218 if (!handler_id_.empty()) {
219 handler = FileHandlerForId(*extension, handler_id_);
220 if (handler) {
221 for (size_t i = 0; i < file_paths_.size(); ++i) {
222 if (!FileHandlerCanHandleFile(
223 *handler, mime_types_[i], file_paths_[i])) {
224 LOG(WARNING)
225 << "Extension does not provide a valid file handler for "
226 << file_paths_[i].value();
227 handler = NULL;
228 break;
232 } else {
233 std::set<std::pair<base::FilePath, std::string> > path_and_file_type_set;
234 for (size_t i = 0; i < file_paths_.size(); ++i) {
235 path_and_file_type_set.insert(
236 std::make_pair(file_paths_[i], mime_types_[i]));
238 const std::vector<const extensions::FileHandlerInfo*>& handlers =
239 extensions::app_file_handler_util::FindFileHandlersForFiles(
240 *extension, path_and_file_type_set);
241 if (!handlers.empty())
242 handler = handlers[0];
245 // If this app doesn't have a file handler that supports the file, launch
246 // with no launch data.
247 if (!handler) {
248 LOG(WARNING) << "Extension does not provide a valid file handler.";
249 LaunchWithNoLaunchData();
250 return;
253 if (handler_id_.empty())
254 handler_id_ = handler->id;
256 // Access needs to be granted to the file for the process associated with
257 // the extension. To do this the ExtensionHost is needed. This might not be
258 // available, or it might be in the process of being unloaded, in which case
259 // the lazy background task queue is used to load the extension and then
260 // call back to us.
261 extensions::LazyBackgroundTaskQueue* const queue =
262 extensions::LazyBackgroundTaskQueue::Get(profile_);
263 if (queue->ShouldEnqueueTask(profile_, extension)) {
264 queue->AddPendingTask(
265 profile_, extension_id,
266 base::Bind(&PlatformAppPathLauncher::GrantAccessToFilesAndLaunch,
267 this));
268 return;
271 extensions::ProcessManager* const process_manager =
272 extensions::ProcessManager::Get(profile_);
273 ExtensionHost* const host =
274 process_manager->GetBackgroundHostForExtension(extension_id);
275 DCHECK(host);
276 GrantAccessToFilesAndLaunch(host);
279 void GrantAccessToFilesAndLaunch(ExtensionHost* host) {
280 const Extension* extension = GetExtension();
281 if (!extension)
282 return;
284 // If there was an error loading the app page, |host| will be NULL.
285 if (!host) {
286 LOG(ERROR) << "Could not load app page for " << extension_id;
287 return;
290 std::vector<GrantedFileEntry> file_entries;
291 for (size_t i = 0; i < file_paths_.size(); ++i) {
292 file_entries.push_back(CreateFileEntry(
293 profile_, extension, host->render_process_host()->GetID(),
294 file_paths_[i], false));
297 AppRuntimeEventRouter::DispatchOnLaunchedEventWithFileEntries(
298 profile_, extension, handler_id_, mime_types_, file_entries);
301 const Extension* GetExtension() const {
302 return extensions::ExtensionRegistry::Get(profile_)->GetExtensionById(
303 extension_id, extensions::ExtensionRegistry::EVERYTHING);
306 // The profile the app should be run in.
307 Profile* profile_;
308 // The id of the extension providing the app. A pointer to the extension is
309 // not kept as the extension may be unloaded and deleted during the course of
310 // the launch.
311 const std::string extension_id;
312 // The path to be passed through to the app.
313 std::vector<base::FilePath> file_paths_;
314 std::vector<std::string> mime_types_;
315 // The ID of the file handler used to launch the app.
316 std::string handler_id_;
317 extensions::app_file_handler_util::MimeTypeCollector collector_;
319 DISALLOW_COPY_AND_ASSIGN(PlatformAppPathLauncher);
322 } // namespace
324 void LaunchPlatformAppWithCommandLine(Profile* profile,
325 const Extension* extension,
326 const base::CommandLine& command_line,
327 const base::FilePath& current_directory,
328 extensions::AppLaunchSource source) {
329 // An app with "kiosk_only" should not be installed and launched
330 // outside of ChromeOS kiosk mode in the first place. This is a defensive
331 // check in case this scenario does occur.
332 if (extensions::KioskModeInfo::IsKioskOnly(extension)) {
333 bool in_kiosk_mode = false;
334 #if defined(OS_CHROMEOS)
335 user_manager::UserManager* user_manager = user_manager::UserManager::Get();
336 in_kiosk_mode = user_manager && user_manager->IsLoggedInAsKioskApp();
337 #endif
338 if (!in_kiosk_mode) {
339 LOG(ERROR) << "App with 'kiosk_only' attribute must be run in "
340 << " ChromeOS kiosk mode.";
341 NOTREACHED();
342 return;
346 #if defined(OS_WIN)
347 base::CommandLine::StringType about_blank_url(
348 base::ASCIIToUTF16(url::kAboutBlankURL));
349 #else
350 base::CommandLine::StringType about_blank_url(url::kAboutBlankURL);
351 #endif
352 base::CommandLine::StringVector args = command_line.GetArgs();
353 // Browser tests will add about:blank to the command line. This should
354 // never be interpreted as a file to open, as doing so with an app that
355 // has write access will result in a file 'about' being created, which
356 // causes problems on the bots.
357 if (args.empty() || (command_line.HasSwitch(switches::kTestType) &&
358 args[0] == about_blank_url)) {
359 AppRuntimeEventRouter::DispatchOnLaunchedEvent(profile, extension, source);
360 return;
363 base::FilePath file_path(command_line.GetArgs()[0]);
364 scoped_refptr<PlatformAppPathLauncher> launcher =
365 new PlatformAppPathLauncher(profile, extension, file_path);
366 launcher->LaunchWithRelativePath(current_directory);
369 void LaunchPlatformAppWithPath(Profile* profile,
370 const Extension* extension,
371 const base::FilePath& file_path) {
372 scoped_refptr<PlatformAppPathLauncher> launcher =
373 new PlatformAppPathLauncher(profile, extension, file_path);
374 launcher->Launch();
377 void LaunchPlatformApp(Profile* profile,
378 const Extension* extension,
379 extensions::AppLaunchSource source) {
380 LaunchPlatformAppWithCommandLine(
381 profile,
382 extension,
383 base::CommandLine(base::CommandLine::NO_PROGRAM),
384 base::FilePath(),
385 source);
388 void LaunchPlatformAppWithFileHandler(
389 Profile* profile,
390 const Extension* extension,
391 const std::string& handler_id,
392 const std::vector<base::FilePath>& file_paths) {
393 scoped_refptr<PlatformAppPathLauncher> launcher =
394 new PlatformAppPathLauncher(profile, extension, file_paths);
395 launcher->LaunchWithHandler(handler_id);
398 void RestartPlatformApp(Profile* profile, const Extension* extension) {
399 EventRouter* event_router = EventRouter::Get(profile);
400 bool listening_to_restart = event_router->
401 ExtensionHasEventListener(extension->id(),
402 app_runtime::OnRestarted::kEventName);
404 if (listening_to_restart) {
405 AppRuntimeEventRouter::DispatchOnRestartedEvent(profile, extension);
406 return;
409 extensions::ExtensionPrefs* extension_prefs =
410 extensions::ExtensionPrefs::Get(profile);
411 bool had_windows = extension_prefs->IsActive(extension->id());
412 extension_prefs->SetIsActive(extension->id(), false);
413 bool listening_to_launch = event_router->
414 ExtensionHasEventListener(extension->id(),
415 app_runtime::OnLaunched::kEventName);
417 if (listening_to_launch && had_windows) {
418 AppRuntimeEventRouter::DispatchOnLaunchedEvent(
419 profile, extension, extensions::SOURCE_RESTART);
423 void LaunchPlatformAppWithUrl(Profile* profile,
424 const Extension* extension,
425 const std::string& handler_id,
426 const GURL& url,
427 const GURL& referrer_url) {
428 AppRuntimeEventRouter::DispatchOnLaunchedEventWithUrl(
429 profile, extension, handler_id, url, referrer_url);
432 } // namespace apps